I read lot of topics (here and otherwehere) about setTimeout and this binding.
Anyway there's something I need to better understand.
I start with below example.
let myObj = {
p: 'my property',
m() { console.log(this.p); }
}
setTimeout(myObj.m, 100); // undefined
setTimeout(function() {myObj.m()}, 100); // 'my property'
What I read from DOC is
Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the window (or global) object. It will not be the same as the this value for the function that called setTimeout.
And a way to fix using function wrapper
A common way to solve the problem is to use a wrapper function that sets this to the required
as I did in the last statement of the snippet.
My doubt: why passing a method by obj to setTimeout without wrapping it doesn't work? Passing object.method should set this to the object anyway. But maybe the direct setTimeout invocation overrides it, forcing this to be window.
I thought that maybe the use of a wrapper function, creates a new underlying scope that can refer to myObj by closure, and subsequently calling setTimeout(myObj.m(), 100) sets the right this.
Thank in advance