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() required中。我在这里有什么ECMAScript 6替代方案来处理这个问题?这是唯一的解决方案,似乎我不能在这里应用箭头。
发布于 2015-09-26 13:48:42
为了直接回答您的问题,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方法将不会出现任何错误。这是因为在this方法的主体中不使用onError:
// Safe unbound method
Person.prototype.onError = function (error) {
console.log(error);
};
// Unsafe unbound method
Person.prototype.onError = function (error) {
console.log(this, error);
// ^^^^
};发布于 2015-09-26 13:14:02
您可以使用脂肪箭头函数
request('http://google.fr').on('error', (error) => this.onError(error));https://stackoverflow.com/questions/32797573
复制相似问题