将承诺处理程序绑定到其类的更好方法

Better way of binding a promise handler to its class

本文关键字:更好 方法 承诺 处理 程序 绑定      更新时间:2023-09-26

我有一个类,它有一个样板函数来处理我的承诺中的错误。

export class AuthError {
  constructor () {
    this.foo = "Something important!";
  }
  catch (e) {
    if (e.hasAProblem) this.foo.bar();
  }
}

我的问题是,当我在其他类中使用此函数作为处理程序时,它当然绑定到 window。

myFunApiCall('baz').catch(authError.catch);

我可以用.bind来解决这个问题

myFunApiCall('baz').catch(authError.catch.bind(authError));

但我真的不喜欢这种语法,尤其是当我知道我的 catch 函数永远不会希望this引用其类以外的任何内容时。

有没有办法给我的函数一个永久的this引用它的类?

如果在构造函数中定义 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()方法都是预绑定到它来自的实例的唯一函数。