Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use 'Array.prototype' and when to use 'this' in JavaScript?

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.

like image 578
Rajat Saxena Avatar asked Dec 18 '16 13:12

Rajat Saxena


People also ask

What is the use of array prototype in JavaScript?

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.

What is the use of array prototype?

prototype allows you to add new properties and methods to arrays. prototype is a property available with all JavaScript objects.

Can I use array prototype at ()?

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.

What is the difference between __ proto __ and prototype?

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.


1 Answers

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.

like image 197
T.J. Crowder Avatar answered Sep 28 '22 03:09

T.J. Crowder