Let's take this example from The Good Parts
book:
Array.method('unshift', function () {
this.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(arguments)));
return this;
});
Why did the author use this.splice
in one place and Array.prototype.slice
in other?
I tried swapping out this
and Array.prototype
with each other and got errors like the following:
TypeError: Cannot read property 'slice' of undefined
but I am still not sure about, how to know when to should use this
or Array.prototype
.
The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will available for every array. When constructing a property, All arrays will be given the property, and its value, as default.
prototype allows you to add new properties and methods to arrays. prototype is a property available with all JavaScript objects.
Array.prototype.at() The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.
In the first call, this
refers to the array on which unshift
was called, and so it inherits splice
from Array.prototype
.
In the second call, though, the code uses slice
on something that isn't an array (the arguments
pseudo-array, which doesn't have a slice
method). So in that case, Crockford accessed the method via Array.prototype
.
Technically, he could have used this.slice
in the second location, like this:
Array.method('unshift', function () {
this.splice.apply(this,[0,0].concat(this.slice.apply(arguments)));
return this;
});
...but it probably would have been misleading, since the second call has nothing to do with the current array referenced by this
.
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