【发布时间】:2017-03-04 09:23:55
【问题描述】:
我想直接从对象本身获取对象的上下文。
例如,在下面的代码中,将使用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 - 在这个简化的示例中,是的 - 我可以使用
_this.data。但是,很多时候我希望正确绑定回调的上下文。
标签: javascript callback