[英]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.