繁体   English   中英

在Array.prototype中获取调用者

[英]Get caller in Array.prototype

我这样做

Array.prototype.foo = function (){
  return this.concat(this);
};

a = [1,2,3];
a.foo(); 
a; // [1,2,3,1,2,3]

如何在Array.prototype.foo中定义变量? 如果我尝试像这样的somtehing:

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

你无法重新分配“这个”。 您可以为“a”变量分配新值。

Array.prototype.foo = function (){
 return this.concat(this);
};

a = [1,2,3];
a = a.foo();
console.log(a);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM