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

26
我试图在回调函数调用后将类开头声明的一个布尔变量设置为 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);
    }
  });  
}
连接到 Braintree Payments 并等待用户支付信息。一旦他们提交表单,我需要将变量 "this.nonReceived" 设置为 true。

2
绑定this或使用箭头函数。 - Andrew Li
我该如何绑定它? - Tristan C
1
请看这里 - Andrew Li
1
在我的例子中,这会是什么样子?bind函数应该放在哪里? - Tristan C
1个回答

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

3
这个绑定是在函数被调用的地方还是在函数定义的地方? - Tristan C
它有所帮助,谢谢 :) - Arash
谢谢。在拖放文件到 div 上时,ES5 语法对我有用。 - Syed Nasir Abbas
这段代码可能对一些人有所帮助: this.dndContainer.ondrop = function (e: any) { e.preventDefault(); e.stopPropagation() this.className = ""; var droppedFiles = e.dataTransfer.files; this.fileStore.push.apply(this.fileStore, droppedFiles); if (this.fileStore.length > 0) { document.getElementById("divDroppedFiles").style.display = "block"; } return false; }.bind(this); - Syed Nasir Abbas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接