xtrom0rt xtrom0rt - 8 days ago 5
Javascript Question

dropzone.js: __slice = [].slice

I'm in the middle of trying to figure out at least parts of enyo's fantastic dropzone.js. I'm fairly green with JavaScript train of thought and the prototype paradigm. There's a line of code right on the fourth row that I'm wondering what it does and why would one use a line like that. The line looks as follows:

var __slice = [].slice


Have I understood correctly, that this takes the slice function from the array prototype object and just gives it a bit easier way to refer to it? What is the benefit of this approach? And why the double-underscore at the beginning? I read somewhere, that this would be to avoid conflicts in the global scope, but isn't this already avoided by wrapping the whole code in the

(function() { //code here
}).call(this);


construct?

Answer

Have I understood correctly, that this takes the slice function from the array prototype object and just gives it a bit easier way to refer to it?

Yes.

What is the benefit of this approach?

__slice is shorter than Array.prototype.slice (which also requires a couple of extra layers of property lookup), and [].slice in theory creates and throws away an object. So having an identifier for it is just saving some typing and the tiniest, tiniest, tiniest bit of runtime performance.

And why the double-underscore at the beginning? I read somewhere, that this would be to avoid conflicts in the global scope, but isn't this already avoided by wrapping the whole code in the ...

Yes, it is already avoided by doing that. In this case, it would just be a convention the author wanted to use, perhaps to indicate that this is his/her shortcut to Array.prototype.slice. The __ has no intrinsic meaning.

Comments