Roka545 Roka545 - 1 year ago 84
AngularJS Question

Use outside variables inside a TypeScript function.

I have this variable:

public originalData: Array<any> = [];

and this function:

canvas.onclick = function (evt) {

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 Source

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

For your application it looks like this:

canvas.onclick = (evt) => {

Or even:

canvas.onclick = e => console.log(this.originalData);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download