the object F has a function stored as this.fn and this.state.fn. can be called successfully as f.fn() but not as f.state.fn()
function F( i, f ) {
this.i = i;
this.state = { 'fn':f };
this.f = f;
};
F.prototype.inc = function() { this.i++ };
F.prototype.fn = function() { this.state.fn() };
f1 = new F( 1, function() { console.log( this.i ); } );
f1.f(); // this works
f1.inc(); // this works
f1.state.fn; // prints the function
f1.fn(); // undefined!
f1.state.fn(); // undefined!
the problem seems to be that the function is stored in the object state, because this works:
f1.state.fn.call( f1 );
F.prototype.fn = function() { this.state.fn.call(this); };
which seems to imply that the this context within F.state.fn is not F but rather F.state – which to me is completely counter-intuitive – is this right!?
Within a function,
thisdepends entirely on how you called the function.When you call a function using dot notation from an object
thiswill be automatically set to that object.If you say
someObject.someChildObject.someFunction()then withinsomeFunction()you’ll findthiswill be set tosomeChildObject.So in your example
f1.fn()should result inthisbeingf1withinfn(), but then within that function you saythis.state.fn()– which will callstate‘sfn()withthisset tostate.You can override this behaviour using
callorapply.Another example just for your interest:
If you create a reference to a function originally defined as an object property and call the function via that reference then
thiswill be whatever applies to your new reference. In my example thexreference is a global, which in practice means it belongs to thewindowobject. What you can learn from this is that the function thatf1.f()calls doesn’t really belong tof1at all.Continuing that example:
When you call
f2.f(), you’ll findthisis set tof2, and because I’ve set a propertyf2.ithe function will log that property.