In the context of inside a function, here’s the code (based on the standard pattern of making a function’s ‘arguments’ into an array):
var args = Array.prototype.slice.call(arguments);
I’m trying to study this out (am a beginner at JavaScript, coming from C#).
I understand that slice is an instance method due to it being a prototype function of Array.
I also understand that this is not a static ‘utility function’, meaning to use it, you have to new it up like so: (example) var myArray = new Array(); myArray.slice(...);
call passes an object in here to change the context to that of arguments
Related to this, I don’t also know the difference between
Array.prototype.slice.call([32,32,121,412]) and Array.prototype.slice([32,32,121,412]) not in the context of call.
So, here’s my question:
I just don’t get how this works in relation to instance vs static methods… so can anyone explain the intricacies of var args = Array.prototype.slice.call(arguments);?
Why can this be used without calling new?
Why was this possible? It’s not a Static method, and it must be ‘newed’ up, and it only works when you use call function… (at least in my C# mentality…)
Unlike C#/Java, functions are actually first-class citizens in JavaScript.
In a general sense:
This means there is no need to “new” it up.. it works exactly as it is because it is its own object.
“new”ing up a function (in a general sense) merely changes the ‘this’ value of that function to the variable it will be assigned to, then returns it.
It is possible to use a function in JavaScript without “newing” it up because they are “first-class citizens” in JavaScript.
In a more in-depth sense, this is what “new” does:
– it creates a new object deriving from MyConstructor.prototype
– it assigns the ‘this’ value of the constructor function to the new object
– execute the code inside (adds properties to new object/instance)
– returns the new object
Some extra notes about what I learned from instances:
– they don’t have a .prototype property like their constructor functions
– though they have a [[prototype]] property, derived from MyConstructor.prototype
– overriding a property in the instance shadows the MyConstructor.prototype[property]..