【问题标题】:Manipulate the `this` object using a newly created Array.prototype method [duplicate]使用新创建的 Array.prototype 方法操作 `this` 对象 [重复]
【发布时间】:2023-02-07 02:07:07
【问题描述】:

我正在尝试完全像这样在 Javascript 中扩展 Array 对象。我正在尝试使用函数中的原型来操作数组的值(存在于 this 对象中)。

function clear() {
    this = [];
}
Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true, });

它给我一个错误 Uncaught SyntaxError: Invalid left-hand side in assignment

我知道 this 是不可变的。解决方法是什么?我不希望创建一个模拟 Array 构造函数的新对象。

【问题讨论】:

    标签: javascript arrays object this prototype


    【解决方案1】:

    一种选择是

    this.splice(0, this.length)
    

    我想你也可以直接做this.length=0,但感觉有点hacky。

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2021-11-01
      • 2017-11-01
      • 2018-05-25
      相关资源
      最近更新 更多