javascript - 在 JavaScript 中什么时候使用 'Array.prototype' 什么时候使用 'this'?

标签 javascript arrays

让我们以 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

我尝试将 thisArray.prototype 相互交换,但出现如下错误:

类型错误:无法读取未定义的属性“切片”

但我仍然不确定,如何知道何时应该使用 thisArray.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/

相关文章:

javascript - 部署 QML 应用程序时找不到 SQLite 数据库

php - 使用 javascript 获取最后添加的字段数

javascript - 在 converseJS 插件中阅读自定义节?

javascript - 单元格之间的链接不是 "flat"- JointJS

c - 我的循环不会检查 C 中数组的所有元素

python - 关于 "f-strings now support = for quick and easy debugging",如何打印 `f' {array[{i=}]= }'` ,索引也为 "="-expanded ?

javascript - JQuery 4按钮菜单,点击隐藏div并显示其他div,反之亦然

c - 从 uint8_t 数组的四个元素中获取 uint32_t 的优雅方式?

java - 将字符串数组从java传递给pl/sql函数

python - 有选择地否定数组中的元素