[英]Modifying “this” variables
我當時在修改數組原型,但是我對此感到困惑。 如果您能幫助我,那就太好了。
好吧,假設我要向Array.prototype添加函數“ Parent”
Array.prototype.Parent = function() {
console.log(this);
}
接下來,我要向父函數添加子函數。 我會這樣做:
Array.prototype.Parent.Child = function() {
console.log(this);
}
現在,我希望在“父級”和“子級”中都引用數組本身。 所以:
[1,2,3].Parent(); // Would output [1,2,3];
[1,2,3].Parent.Child(); // Want it to print [1,2,3];
基本上,我希望子級中的此變量引用數組而不是父函數。 有見識嗎?
您可以使Parent
為獲取器,為每個數組返回唯一的函數,並提供上下文:
Object.defineProperty(Array.prototype, 'parent', {
configurable: true,
get: function () {
var that = this;
function parent() {
console.log(that);
}
parent.child = function () {
console.log(that);
};
return parent;
},
});
這里的問題是,如果您先進行一系列對象查找,然后進行函數調用,則如何識別this
變量。 像這樣。
foo.bar.baz.qux();
qux方法的this值等於foo.bar.baz
。 因此,從本質上講,javascript中的函數具有一個隱藏的參數, this
是它們被調用的對象。
無法在javascript中修改此行為。
您可以使用Function.bind
重新分配this
。
var myArray = [1,2,3];
myArray.Parent.Child.bind( myArray )();
在我的例子, myArray.Parent.Child
是Function
,你在你的例子定義-然后我們用bind
創建函數的副本, this
設置為myArray
,然后我們使用()
操作符來調用它。
可以使用自動執行的lambda(ES6)將其減少為一行:
( x => x.Parent.Child.bind( x )() )( myArray );
...等效於ES5:
( function( x ){ return x.Parent.Child.bind( x )() } )( myArray );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.