Qwe Qwe
Qwe Qwe

Reputation: 495

Javascript Cannot read property 'x' of undefined

I don't understand the error in the code below. I tried calling another class's function from another class. But I gives the error error: Uncaught TypeError: Cannot read property '_name' of undefined

class Person {
    constructor() {
        this._name = "Name-Person";
    }

    getName() {
        return this._name;
    }
}

class Test1 {
    constructor() {
        let p = new Person();
        new Test2(p.getName);
    }
}

class Test2 {
    constructor(getName) {
        console.log(getName());
    }
}

new Test1()

How can I fix the error?

Upvotes: 3

Views: 260

Answers (3)

einord
einord

Reputation: 2325

Because you are passing the function and not the entire class or its value, _name does not exist in the context of the Test2 constructor.

A couple of simple solutions is to either pass in the result of getName() to the constructor, or the entire class of Person.

new Test2(p); // And in Test2 use p.getName()

// or

new Test2(p.getName()); // And in Test2 use the result

Upvotes: 0

Alan Omar
Alan Omar

Reputation: 4217

you can use public class field:

class Person {
    constructor() {
        this._name = "Name-Person";
    }

    getName = () => {
        return this._name;
    }
}

class Test1 {
    constructor() {
        let p = new Person();
        new Test2(p.getName);
    }
}

class Test2 {
    constructor(getName) {
        console.log(getName());
    }
}

new Test1()

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

When passing the function to Test2 you need to bind p to the function

new Test2(p.getName.bind(p));

class Person {
    constructor() {
        this._name = "Name-Person";
    }

    getName() {
        return this._name;
    }
}

class Test1 {
    constructor() {
        let p = new Person();
        new Test2(p.getName.bind(p));
    }
}

class Test2 {
    constructor(getName) {
        console.log(getName());
    }
}

new Test1()

Upvotes: 5

Related Questions