Roka545 Roka545 - 4 months ago 10
AngularJS Question

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?

Answer

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);