0

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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.