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

Tri*_*n C 6 javascript braintree typescript

我试图在调用回调时将在类的开头声明的变量(布尔值)设置为true,但我一直在获取TypeScript erorr.

这是错误:

TypeError: Cannot set property 'nonReceived' of undefined
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

  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);
    }
  });  
}
Run Code Online (Sandbox Code Playgroud)

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

Kon*_*sky 24

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

  • 绑定会进入调用函数的位置还是函数定义? (3认同)