【问题标题】:How to access 'this' inside a callback function in Typescript? [duplicate]如何在 Typescript 的回调函数中访问“this”? [复制]
【发布时间】:2017-03-14 04:54:33
【问题描述】:

一旦调用回调,我试图将在类开头声明的变量(布尔值)设置为 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。

【问题讨论】:

  • 绑定this或使用箭头函数
  • 如何绑定这个?
  • here
  • 在我的示例中会是什么样子?绑定函数会去哪里?

标签: javascript typescript braintree


【解决方案1】:

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

【讨论】:

  • 绑定到函数被调用的地方还是函数定义?
  • 帮了大忙,谢谢:)
  • 谢谢。 ES5 语法在 ondrop 中为我工作,用于在 div 上拖放文件。
  • 这段代码可能对某人有帮助: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"; } 返回假; }.bind(this);
猜你喜欢
  • 2018-05-05
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多