I have seen people using two different ways of using different methods of the Array object in javascript.
I mostly use it like so:
arr.push(element1, ..., elementN)
But I have seen people using this:
Array.prototype.push.apply(this,arguments)
I understand that all JavaScript objects inherit the properties and methods from their prototype. The Object.prototype is on the top of the prototype chain.
What are the differences between two approaches and when should each approach be used?
The call via .apply()
is used when you're interested in using .push()
with an object that isn't really an array. A jQuery object, for example, is not really an array instance, but the code mostly maintains a .length
property that's enough for it to look like an array, at least as far as .push()
and other Array prototype methods are concerned.
For a real array instance, there's no need to do that; the .push()
method is directly available via the prototype chain.
So:
var obj = { length: 0 };
Array.prototype.push.apply(obj, ["hello world"]);
console.log(obj[0]); // hello world
I assume you saw Array.prototype.push.apply(this,arguments)
in an function like this
function foo() {
arguments.push = function() {
Array.prototype.push.apply(this,arguments);
}
arguments.push(1,2,3);
//....
}
Here this is the foo's arguments
, it is just an Array like object, not an Array, it does not have push method. So we should use Array.prototype.push.apply(this,arguments)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With