Iago Chaves
Iago Chaves

Reputation: 37

This context undefined in the parent class

I came across the following scenario:

abstract class Base {
    public _obj = { name: 'Test' }

    print1() {
        console.log(this._obj)
    }

    print2() {
        console.log(this)
    }
}

class Child extends Base {
    print2() { // overriding
        // do some stuff
        console.log(this._obj)
    }
}

function test(cb: any) {
    cb()
}

const obj = new Child()
obj.print1() // ok!
obj.print2() // ok!
test(obj.print1) // undefined

Playground

If I print the this it will be undefined. Why when I pass the function as a parameter I lose the this context?

Thank you.

Upvotes: 0

Views: 135

Answers (1)

basarat
basarat

Reputation: 276105

Why when I pass the function as a parameter I lose the this context?

That is how this works in JavaScript. From your code the issue is highlighted:

function test(cb: any) {
    cb() // `this` is undefined
}

Fix

Simplest fix would be to pass in a function that does not depend on this e.g.: test(() => obj.print1())

Complete code:

abstract class Base {
    public _obj = { name: 'Test' }

    print1() {
        console.log(this._obj)
    }

    print2() {
        console.log(this)
    }
}

class Child extends Base {
    print2() { // overriding
        // do some stuff
        console.log(this._obj)
    }
}

function test(cb: any) {
    cb() // `this` is undefined
}

const obj = new Child()
obj.print1() // ok!
obj.print2() // ok!
test(() => obj.print1())

Additional Resources

I also have a video on the subject 🌹

Upvotes: 3

Related Questions