0
我想直接從對象本身獲取對象的上下文。直接從對象中獲取對象的上下文
例如,在下面的代碼中,將使用mousedown
事件調用回調函數。它正常工作,因爲我使用this.callback.bind(this))
綁定回調。
作爲一個接口,這是相當笨拙。我希望能夠簡單地通過this.callback
並從MyClass2
中找出回調函數的上下文並將其綁定到接收端。這可能嗎?
function MyClass1() {
var _this = this;
this.data = "Foo";
var div = document.getElementById("div");
this.callback = function() {
console.log("Callback: " + this.data);
}
var m2 = new MyClass2(div, this.callback.bind(this));
}
function MyClass2(div, callback) {
var _this = this;
// I'd like to bind callback to the context it had when it was passed here
// e.g. this.callback = callback.bind(callback.originalContext);
this.callback = callback;
div.addEventListener("mousedown", function(e) {
_this.mousedown.call(_this, e)
});
this.mousedown = function() {
console.log("Mousedown");
this.callback();
}
}
var m1 = new MyClass1();
<div id="div" style="background-color:azure; height:100%; width:100%">
Click me
</div>
難道你不能在回調函數中使用現有的'_this'變量而不是'this'嗎? – nnnnnn
@nnnnnn - 在這個簡化的例子中,是的 - 我可以使用'_this.data'。不過,有很多次我希望回調的上下文被正確綁定。 – mseifert