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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40353503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:58:44  来源:igfitidea点击:

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

javascripttypescriptbraintree

提问by Tristan C

I am trying to set a variable declared at the beginning of the class (a boolean) to true once a callback is called, but I keep getting a TypeScript erorr.

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

Here is the error:

这是错误:

TypeError: Cannot set property 'nonReceived' of undefined

Here is my code:

这是我的代码:

  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);
    }
  });  
}

The brintree-setup connect to Braintree Payments, and awaits user payment info. Once they submit the form, I need the variable "this.nonReceived" to be set to true.

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

回答by Konstantin Vitkovsky

If you use ES5 syntax you could use function(){}.bind(this)to bind the callback with the context but with Typescript you can use ES6 syntax and use arrow function (parameters) => {function_body}which bind current context implicitly.

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