You are losing the bind of this
to your method.
Change from this:
setTimeout(this.talk, 5000, 'hello again');
to this:
setTimeout(this.talk.bind(this), 5000, 'hello again');
When you pass this.talk
as a function argument, it takes this
and looks up the method talk
and passes a reference to that function. But, it only passes a reference to that function. There is no longer any association with the object you had in this
. .bind()
allows you to pass a reference to a tiny stub function that will keep track of this
and call your method as this.say()
, not just as say()
.
You can see the same thing if you just did this:
const talker = new Talker();'
const fn = talker.say;
fn();
This would generate the same issue because assigning the method to fn
takes no associate to talker
with it at all. It's just a function reference without any association with an object. In fact:
talker.say === Talker.prototype.say
What .bind()
does is create a small stub function that will save the object value and will then call your method using that object.