将 promise 处理程序绑定到其 class 的更好方法
Better way of binding a promise handler to its class
我有一个 class,它有一个单一的样板函数来处理我承诺的错误。
export class AuthError {
constructor () {
this.foo = "Something important!";
}
catch (e) {
if (e.hasAProblem) this.foo.bar();
}
}
我的问题是,当我在其他 classes 中使用此函数作为处理程序时,它当然会绑定到 window。
myFunApiCall('baz').catch(authError.catch);
我可以用 .bind
解决这个问题
myFunApiCall('baz').catch(authError.catch.bind(authError));
但我真的不喜欢这种语法,尤其是当我知道我的 catch 函数永远不会希望 this
引用它的 class 以外的任何东西时。
有没有办法让我的函数永久 this
引用它的 class?
如果您在构造函数中定义了 catch
方法,您可以通过这样声明来强制将方法绑定到它的对象:
function AuthError() {
this.foo = "Something important!";
this.catch = function() {
// use this here
}.bind(this);
}
var authError = new AuthError();
myFunApiCall('baz').catch(authError.catch);
这使得该类型的每个对象上的每个 .catch()
方法都是一个唯一的函数,该函数预先绑定到它来自的实例。
我有一个 class,它有一个单一的样板函数来处理我承诺的错误。
export class AuthError {
constructor () {
this.foo = "Something important!";
}
catch (e) {
if (e.hasAProblem) this.foo.bar();
}
}
我的问题是,当我在其他 classes 中使用此函数作为处理程序时,它当然会绑定到 window。
myFunApiCall('baz').catch(authError.catch);
我可以用 .bind
myFunApiCall('baz').catch(authError.catch.bind(authError));
但我真的不喜欢这种语法,尤其是当我知道我的 catch 函数永远不会希望 this
引用它的 class 以外的任何东西时。
有没有办法让我的函数永久 this
引用它的 class?
如果您在构造函数中定义了 catch
方法,您可以通过这样声明来强制将方法绑定到它的对象:
function AuthError() {
this.foo = "Something important!";
this.catch = function() {
// use this here
}.bind(this);
}
var authError = new AuthError();
myFunApiCall('baz').catch(authError.catch);
这使得该类型的每个对象上的每个 .catch()
方法都是一个唯一的函数,该函数预先绑定到它来自的实例。