我有一个JavaScript类,有两个方法,如this。
var MyObject = function () {};
MyObject.prototype = {
open: function () {
var self = this;
console.log(self);
$('#a').click('', self.other);
},
other: function () {
console.log(this);
}
};
var myobject = new MyObject;
myobject.open();
在console.log
函数的other
中,this
是事件侦听的HTML节点,而不是MyObject
中的open
对象功能
如何在用作回调时从函数MyObject
中检索other
对象?
答案 0 :(得分:1)
您可以使用$.proxy传递this
上下文作为第二个参数:
var MyObject = function () {};
MyObject.prototype = {
open: function () {
$('#a').click($.proxy(this.other, this));
},
other: function () {
console.log(this);
}
};
var myobject = new MyObject;
myobject.open();
点击#a
时,系统会调用MyObject.other()
函数并引用this
实例{/ 1}}。
答案 1 :(得分:1)
您可以将this
传递给eventData
的{{1}}参数。
.click
你看到你的html对象在其他地方登录MyObject.prototype = {
open: function () {
var self = this;
console.log(self);
$('#a').click(self, self.other);
},
other: function (event) {
console.log(event.data); // should output your object
}
};
的原因是因为其他人正在this
回调的上下文中运行而.click
指的是它的来电者 - - > html对象。