相关疑难解决方法(0)

为什么我不能在原型函数中为"this"赋值?

我为什么这样做:

Array.prototype.foo = function() {
    this.splice(0, this.length);
    return this.concat([1,2,3]);
}
Run Code Online (Sandbox Code Playgroud)

但我不能这样做:

Array.prototype.foo = function() {
    return this = [1,2,3];
}
Run Code Online (Sandbox Code Playgroud)

这两个函数都会破坏它的值并将其更改为[1,2,3]但第二个函数会抛出以下错误:Uncaught ReferenceError: Invalid left-hand side in assignment

我怀疑这是因为允许赋值意味着我可能会将数组更改为其他内容(如字符串),但我希望有人确切知道和/或有更详细的解释.

javascript

27
推荐指数
3
解决办法
1万
查看次数

标签 统计

javascript ×1