Can anybody elaborate below in innerF, what does this refer to? User or innerF?
function User(){
this.id = 1;
};
User.prototype.sayHi = function(){
var innerF = function(){
this.id = 2; // "this" refers to User or innerF ?
};
return innerF;
};
Also does the new keyword or anonymous function has to do with changing reference of this keyword?
What if I call it all like this:
var u = User;
var f = u.sayHi();
f();
Or
var u = new User;
var f = u.sayHi();
f();
Thanks
What the
thislocal refers to inside ofinnerFwill depend on how the function is eventually invoked. It can be invoked in a variety of ways that will change the meaning ofthis. For exampleBased on your code though it appears that you want
thisto refer to the instance ofUseron whichsayHiwas invoked. If so then you need to storethisin a local and refer to that local withininnerF.Note though that
thisinsidesayHiisn’t guaranteed to point toUserinstance either. In general it will the same tricks can be done tosayHithat were done toinnerF. For example