让我们以 The Good Parts
一书中的这个例子为例:
Array.method('unshift', function () {
this.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(arguments)));
return this;
});
为什么作者在一处使用了this.splice
,而在另一处使用了Array.prototype.slice
?
我尝试将 this
和 Array.prototype
相互交换,但出现如下错误:
类型错误:无法读取未定义的属性“切片”
但我仍然不确定,如何知道何时应该使用 this
或 Array.prototype
。
最佳答案
在第一次调用中,this
引用了调用unshift
的数组,因此它继承了Array 的
。splice
.原型(prototype)
不过,在第二次调用中,代码在不是数组的对象上使用了slice
(arguments
伪数组,它没有 slice
方法)。因此,在这种情况下,Crockford 通过 Array.prototype
访问该方法。
从技术上讲,他可以在第二个位置使用 this.slice
,如下所示:
Array.method('unshift', function () {
this.splice.apply(this,[0,0].concat(this.slice.apply(arguments)));
return this;
});
...但这可能会产生误导,因为第二次调用与 this
引用的当前数组无关。
关于javascript - 在 JavaScript 中什么时候使用 'Array.prototype' 什么时候使用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41208613/