我试图从方法内部访问对象的成员变量,该方法作为回调传递,在filereader事件期间触发。
我把下面的代码拼凑在一起,试图传达我的观点。似乎'this‘成为文件读取器,而不是调用点的对象。有没有办法让finishLoading能够访问对象变量?
我希望确保回调是为对象量身定做的,否则我只会将它们定义为类外部的静态函数。
function myClass(newName)
{
this.name = newName;
this.m_fileReader = new FileReader();
this.finishedLoading =
function(param1)
{
alert(this.name);
};
this.m_fileReader.addEventListener('loadend',
this.callback_finishedLoading,
false);
}
var instance = new myClass('timmy');
var instance2 = new myClass('joe');
发布于 2013-07-11 20:05:13
您需要.bind
函数:
this.m_fileReader.addEventListener('loadend',
this.callback_finishedLoading.bind(this),
false);
.bind
函数将接受传递的参数,并使用该参数作为其this
来调用原始函数,而不是使用浏览器试图提供的任何值。
或者,只需为this
创建自己的别名,并将调用封装在一个匿名函数中:
var self = this;
this.m_fileReader.addEventListener('loadend', function(ev) {
self.callback_finishedLoading(ev)
}, false);
后者主要是.bind
在幕后做的事情,但它的优点是它可以在ES5之前的浏览器上运行,而不需要填充程序。
发布于 2013-07-11 20:12:04
您可以让构造函数实现EventListener接口,如下所示:
function myClass(newName) {
this.name = newName;
this.m_fileReader = new FileReader();
this.m_fileReader.addEventListener('loadend', this, false);
}
myClass.prototype.handleEvent = function(event) {
return this[event.type] && this[event.type](event)
}
myClass.prototype.loadend = function(event) {
alert(this.name);
};
var instance = new myClass('timmy');
var instance2 = new myClass('joe');
我将finishedLoading
重命名为loadend
,并将其放在构造函数的.prototype
中。然后,我向.prototype
添加了一个.handleEvent
方法。
最后,在构造函数中,我们根本不传递函数。相反,只需传递myClass
实例this
即可。
我删除了你的param1
,因为不清楚它是如何使用的。如果它需要从其他调用接收一些值,那么您可以在.prototype
上创建一个单独的finishedLoading
方法,并让.loadend()
方法调用它。
发布于 2013-07-11 20:06:47
this
是相对于上下文的。每次打开新块{}时,它都会更改为当前块上下文。在调用回调函数之前,将this
保存到另一个变量。
https://stackoverflow.com/questions/17602419
复制相似问题