Reputation: 37
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
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
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
}
Simplest fix would be to pass in a function that does not depend on this
e.g.: test(() => obj.print1())
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())
I also have a video on the subject 🌹
Upvotes: 3