如何在 Typescript 的回调函数中访问 'this'?

How to access 'this' inside a callback function in Typescript?

我试图在调用回调后将 class 开头声明的变量(布尔值)设置为 true,但我一直收到 TypeScript 错误。

这里是错误:

TypeError: Cannot set property 'nonReceived' of undefined

这是我的代码:

  finalizeToken(){
  braintree.setup(JSON.parse(this.finalToken), 'dropin', {
     container: 'dropin-container',
     defaultFirst: true,
      form: 'checkout-form',
      onPaymentMethodReceived: function (obj) {
        this.nonReceived = true;
      localStorage.setItem('nonce', obj.nonce);
    }
  });  
}

brintree-setup 连接到 Braintree Payments,并等待用户支付信息。他们提交表单后,我需要将变量 "this.nonReceived" 设置为 true。

如果您使用 ES5 语法,您可以使用 function(){}.bind(this) 将回调与上下文绑定,但是对于 Typescript,您可以使用 ES6 语法并使用箭头函数 (parameters) => {function_body} 来隐式绑定当前上下文。