替代 ES6 中的 .on('error', this.onError.bind(this)) ?
Alternative to .on('error', this.onError.bind(this)) in ES6?
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 替代方案来处理这个问题?这是唯一的解决方案吗,我似乎不能在此处应用箭头。
您可以使用 fat arrow functions:
request('http://google.fr').on('error', (error) => this.onError(error));
为了直接回答您的问题,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);
// ^^^^
};
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 替代方案来处理这个问题?这是唯一的解决方案吗,我似乎不能在此处应用箭头。
您可以使用 fat arrow functions:
request('http://google.fr').on('error', (error) => this.onError(error));
为了直接回答您的问题,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);
// ^^^^
};