如何在Typescript的回调函数中访问“ this”? [英] How to access 'this' inside a callback function in Typescript?

查看:665
本文介绍了如何在Typescript的回调函数中访问“ this”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是错误:

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设置连接到Braintree Payments,并等待用户付款信息。他们提交表单后,需要将变量 this.nonReceived设置为true。

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.

推荐答案

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

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.

这篇关于如何在Typescript的回调函数中访问“ this”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆