从回调中检索原始上下文
Retrieve origina context from callback
我有一个 JavaScript class 有两种方法,例如 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();
在other
函数中的console.log
中,this
是事件监听的HTML节点,而不是MyObject
中的对象open
函数。
当用作回调时,如何从函数 other
中检索 MyObject
对象?
您可以使用 $.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
.
的 this
实例调用 MyObject.other()
函数
您可以将 this
传递给 .click
的 eventData
参数。
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
}
};
您看到 html 对象在 other 中记录 this
的原因是因为在 .click
回调和 this
指的是它的调用者 --> html 对象。
我有一个 JavaScript class 有两种方法,例如 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();
在other
函数中的console.log
中,this
是事件监听的HTML节点,而不是MyObject
中的对象open
函数。
当用作回调时,如何从函数 other
中检索 MyObject
对象?
您可以使用 $.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
.
this
实例调用 MyObject.other()
函数
您可以将 this
传递给 .click
的 eventData
参数。
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
}
};
您看到 html 对象在 other 中记录 this
的原因是因为在 .click
回调和 this
指的是它的调用者 --> html 对象。