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

Take this example from The Good Parts :

 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 another?

I tried replacing this and Array.prototype with each other and got the following errors:

TypeError: Cannot read property 'slice' of undefined

but I'm still not sure how to know when to use this or Array.prototype .

+5
source share
2 answers

In the first call, this refers to the array that unshift was called unshift , and therefore it inherits splice from Array.prototype .

In the second call, the code uses slice for something that is not an array (a pseudo-array of arguments that does not have a slice method). So in this case, Crockford accessed the method through Array.prototype .

Technically, he could use this.slice in second place, for example:

 Array.method('unshift', function () { this.splice.apply(this,[0,0].concat(this.slice.apply(arguments))); return this; }); 

... but that would probably be wrong, since the second call has nothing to do with the current array referenced by this .

+8
source

Sometimes it's easier to visualize relationships, so you realize that in many cases we have foo.bar === Foo.prototype.bar; // true foo.bar === Foo.prototype.bar; // true

prototype structure

When you create an instance of foo prototype property of the foo constructor is set as a special reference foo ( __proto__ ), where if you are trying to access a property that does not exist directly on foo next place that the property looks for is this link.

This means that if you expect that foo will not be changed in such a way as to hide the property from this object, it does not matter if you try to search through foo.bar or Foo.prototype.bar , since this is one and the same.

However, as you can see, not everyone will have the same __proto__ path, so you could not assume that obj.slice will exist, for example. This means that if you don't have an Array instance, but you want to cut it off, you need to reference the slice, although you know that there is a way like Array.prototype.slice

0
source

Source: https://habr.com/ru/post/1261456/


All Articles