我剛開始使用原型JavaScript,並且無法在範圍更改時從原型函數內部保留對主對象的引用this
。讓我來說明我的意思(我使用jQuery在這裏):在JavaScript原型函數中保留對「this」的引用
MyClass = function() {
this.element = $('#element');
this.myValue = 'something';
// some more code
}
MyClass.prototype.myfunc = function() {
// at this point, "this" refers to the instance of MyClass
this.element.click(function() {
// at this point, "this" refers to the DOM element
// but what if I want to access the original "this.myValue"?
});
}
new MyClass();
我知道我可以通過在myfunc
開始做這個保存到主對象的引用:
var myThis = this;
然後使用myThis.myValue
訪問主對象的屬性。但是當我在MyClass
上有大量的原型函數時會發生什麼?我必須在每個開頭保存對this
的引用嗎?似乎應該有一個更清潔的方式。並且怎麼樣這樣的情況:
MyClass = function() {
this.elements $('.elements');
this.myValue = 'something';
this.elements.each(this.doSomething);
}
MyClass.prototype.doSomething = function() {
// operate on the element
}
new MyClass();
在這種情況下,我不能創建與var myThis = this;
主要對象的引用,因爲this
的doSomething
範圍內,即使原來的值是jQuery
對象,而不是一個MyClass
對象。
有人建議我使用全局變量來保存對原始this
的引用,但對我來說這似乎是一個非常糟糕的主意。我不想污染全局命名空間,這似乎會阻止我實例化兩個不同的對象,而不會相互干擾。
有什麼建議嗎?有沒有乾淨的方式來做我以後的事情?或者是我的整個設計模式有缺陷?
我真的很喜歡這個功能,但是在jQuery環境中,我傾向於在給定現有jQuery.bind方法的情況下命名它(即使沒有實際的命名衝突)。 –
@Rob,創建一個與'Function.prototype.bind'相同的'jQuery.bind'方法是很簡單的,檢查這個簡單的實現:http://jsbin.com/aqavo/edit雖然我會考慮更改它的名字,它可能會導致與事件/綁定方法混淆... – CMS
我強烈建議堅持使用名稱'Function.prototype.bind'。它現在是語言的標準化部分;它不會消失。 – bobince