Tristan C Tristan C - 4 months ago 44
Javascript Question

How to access 'this' inside a callback function in 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.

Here is the error:

TypeError: Cannot set property 'nonReceived' of undefined

Here is my code:

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.


If you use ES5 syntax, like in the code you attached you could use function(){}.bind(this) to bind the callback with the context or you can use ES6 syntax and use arrow function (parameters) => {function_body} which bind current context implicitly.