最可能的情形,其中將this
的FieldEdit
方法執行期間引用非FieldEdit
其它的目的是像一個閉合,事件處理程序,或任何功能或方法與.call(someOtherScope)
或.apply(someOtherScope, args)
明確地稱爲嵌套範圍內。
當然,您可以通過維護對FieldEdit
實例的變量引用並使用FieldEditInstance.<method>()
來解決此問題。
PrototypeJS允許您將與Function.bind
功能用於此目的,但它很容易實現,否則,無論是搭配:
var FieldEditInstance = this;
obj.methodThatUsesACallback(function() {
// use that instead of this
});
OR
var FieldEditInstance = this;
var callback = function() {
// ...
};
// This is more or less what PrototypeJS' Function.bind produces
var boundCallback = function() {
return callback.apply(FieldEditInstance, arguments);
};
obj.methodThatUsesACallback(boundCallback);
啊。事實上,它發生在我構建的自定義事件處理程序的回調函數中。多麼痛苦。 – 2009-07-26 06:27:08