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