0
class MyClass {

    propOne = 'prop 1'
    
    doSomething() {
        console.log('executing doSomething')
        console.log(this.propOne)
    }

    example1() {
        setTimeout(() => { this.doSomething() }, 3000)
    }

    example2() {
        setTimeout(this.doSomething, 3000)
    }
    
}


const obj = new MyClass()

obj.example1()
// LOG: VM1240:6 executing doSomething
// LOG: VM1240:7 prop 1

obj.example2()
// LOG: VM1240:6 executing doSomething
// VM1240:7 undefined

Why obj.example2() prints prop1 undefined?

I know that an arrow function does not have a 'this' value of its own, anyway this does not seem the specific case of this behavior.

  • 1
    `setTimeout` calls the callback like a "normal" function. In a function called that way `this` is either `undefined` (strict mode), the global object (non-strict mode), a bound value (if function was created via `.bind`) or the `this` value of the closest `this`-providing environment (arrow-function). `this.doSomething` is an ordinary method/function and `class`es are always strict, so `this` will be `undefined`. A simple solution is to use `.bind`: `setTimeout(this.doSomething.bind(this), 3000)`. The duplicate has more information. – Felix Kling Apr 13 '22 at 08:20

0 Answers0