0

I'm trying to add an array as a class member in Typescript. But when I try to access it somewhere I get an error that it is undefined. What am missing here?

.html

<button id="storePersonBtn">

.ts

export class App {

    public myArray: Array<Boolean> = [];

    constructor() {
        console.log(this.myArray) //outputs []
        $('#storePersonBtn').click(this.storePerson);
    }

    private storePerson() {
        console.log(this.myArray) //outputs undefined
    }
}

1 Answer 1

1

The problem is JavaScript's this which is bound at the call site. If you write a.b() then this inside b will be set to a. But if you do this:

const b = a.b;
b();

then this inside b is unset.

What you should do is this:

.click(() => this.storePerson())

This way you call storePerson with the proper this.

Sign up to request clarification or add additional context in comments.

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.