将方法作为回调传递的javascript问题

javascript problems with passing methods as callbacks

本文关键字:javascript 问题 回调 方法      更新时间:2023-09-26

我正试图从一个方法内部访问对象的成员变量,该方法作为回调传递,在文件读取器事件期间触发。

我把下面的代码拼凑在一起,只是为了传达我的观点。"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');

您需要.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之前的浏览器上工作,而不需要填充程序。

您可以让构造函数实现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方法。

最后,在构造函数中,我们根本不传递函数。相反,只需传递this,它就是您的myClass实例。

我删除了你的param1,因为不清楚该如何使用。如果它需要从其他调用中接收一些值,那么您可以在.prototype上创建一个单独的finishedLoading方法,并让.loadend()方法调用它

this是相对于上下文的。每次打开新块{}时,它都会更改为当前块上下文。在调用回调函数之前,将this保存到另一个变量中。