Roka545
Roka545

Reputation: 3636

Use outside variables inside a TypeScript function.

I have this variable:

public originalData: Array<any> = [];

and this function:

canvas.onclick = function (evt) {
            console.log(this.originalData);
}

The function is unable to see this.originalData - how do I go about accessing that and other variable properly within my 'onclick' method? I now I can do this outside of the function:

var dataCopy = this.originalData;

and access it via 'dataCopy', but is there a way to access the variable without creating a new var variable?

Upvotes: 0

Views: 2211

Answers (2)

DonO
DonO

Reputation: 1070

This is a little tricky in JavaScript. The this in your function points to the function. Since you are using typescript you probably have a class to wrap the variable and the function. You can try ClassName.originalData

Upvotes: 0

trey-jones
trey-jones

Reputation: 3437

Probably the best way is to use the ES6 arrow function.

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).

For your application it looks like this:

canvas.onclick = (evt) => {
     console.log(this.originalData); 
};

Or even:

canvas.onclick = e => console.log(this.originalData);

Upvotes: 2

Related Questions