ES6中的.on('error', this. onerror .bind(this))的替代方案

Alternative to .on('error', this.onError.bind(this)) in ES6?

本文关键字:this 方案 bind 中的 on error ES6 onerror      更新时间:2023-09-26
function Person()
}
function Person.prototype.init() {   
  request('http://google.fr').on('error', this.onError.bind(this));
}
function Person.prototype.onError(error) {
  console.log(error);
}

bind.this在所需的init()中。我在这里有什么ECMAScript 6替代品来处理这个问题?这是唯一的解决方案吗,我似乎不能在这里使用箭头

直接回答你的问题,ES6没有提供任何额外的功能,我们可以使用它来避免在调用点绑定onError。ES6并没有取消JavaScript执行上下文的行为。

作为旁注,声明实例方法的方式是非法的,并且会抛出错误。它们应该按如下方式声明:

Person.prototype.init = function () {   
    request('http://google.fr').on('error', this.onError.bind(this));
};
Person.prototype.onError = function (error) {
    console.log(error);
};

当前您的onError方法将不会遭受任何错误,如果传递未绑定。这是因为您没有在onError方法的主体内使用this:

// Safe unbound method
Person.prototype.onError = function (error) {
    console.log(error);
};
// Unsafe unbound method
Person.prototype.onError = function (error) {
    console.log(this, error);
             // ^^^^
};

您可以使用胖箭头函数:

request('http://google.fr').on('error', (error) => this.onError(error));