我有一个构造函数,它注册一个事件处理程序:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);Run Code Online (Sandbox Code Playgroud)
但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.
我还尝试使用对象方法而不是匿名函数:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)
但它表现出同样的问题.
如何访问正确的对象?
我知道关于这个话题还有其他一些帖子,但它们仍让我感到困惑.
我已经包含了jQuery和所有内容,我有一个像这个例子的简单的javascript类:
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
$("#kphdiv").html(this.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
Run Code Online (Sandbox Code Playgroud)
现在我知道该代码段不起作用,并且没有正确构建.
"this"关键字引用了我的dom元素,其id为"kphdiv".
我的问题是处理这个问题的最佳方法是什么.
我见过一种方法,你设置一些等于此的变量(绑定它),然后使用该变量来引用你的对象.例如:
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
Run Code Online (Sandbox Code Playgroud)
我也可以让我成为一个全球变量...我不知道.
如果有另一种/更好的方式,我只是好奇.