我正在这样做
Array.prototype.foo = function (){
return this.concat(this);
};
a = [1,2,3];
a.foo();
a; // [1,2,3,1,2,3]
如何在 Array.prototype.foo 中定义变量?如果我尝试这样的事情:
this = this.concat(this)
我收到一个错误:
“ReferenceError:分配中的左侧无效”
我正在这样做
Array.prototype.foo = function (){
return this.concat(this);
};
a = [1,2,3];
a.foo();
a; // [1,2,3,1,2,3]
如何在 Array.prototype.foo 中定义变量?如果我尝试这样的事情:
this = this.concat(this)
我收到一个错误:
“ReferenceError:分配中的左侧无效”
您不能分配给this
关键字。要更改当前对象,您必须通过更改其属性来修改它。
Array.prototype.foo = function (){
Array.prototype.push.apply(this, this);
return this;
};
a = [1,2,3];
a.foo();
a; // [1,2,3,1,2,3]
您当前的代码执行return
一个新实例,您需要将其重新分配给a
.
您不能重新分配“this”。不过,您可以为“a”变量分配一个新值。
Array.prototype.foo = function (){
return this.concat(this);
};
a = [1,2,3];
a = a.foo();
console.log(a);