The previous answers only gave you code samples on how to fix it; Let me explain your issue and why it's happening
In your code example, the function inside of your setTimeout is being bound to the this
value of the setTimeout (which is generally window
or undefined
in strict mode).
setTimeout(function () {
// this === window
}, 1000);
In ES6, they introduced lambda expressions (arrow functions) which are "lexically bound" -- meaning that they borrow the this
value from their outside scope. In your case, that's the class/object.
In order to leverage the lambda expressions, it would look like:
class Foo {
constructor () {
setTimeout(() => this.myMethod(), 1000);
}
myMethod () {
console.log('foo');
}
}
If you're using Babel to transpile your code, and are using experimental features, you can use ES7's binding syntax to solve your problem as well.
If you bind a function/method, it creates a copy of that function, and binds the this
value to whatever you choose. This will allow you to use the function
statement that will be bound to your class/object.
<context to be bound> :: <function to receive context>
class Foo {
constructor () {
setTimeout(this::function() {
this.myMethod();
}, 1000);
}
myMethod () {
console.log('foo');
}
}
An even shorter version would look something like the following
constructor () {
setTimeout(this::this.myMethod, 1000);
}
If you're still having issues understanding this, I suggest you read more about ES6 classes and javascript binding.