This is taken from John Resig`s Learning Advanced Javascript #25, called changing the context of a function.
1) in the line fn() == this what does this refer to? is it referring to the this inside the function where it says return this?
2) although I understand the purpose of the last line (to attach the function to a specific object), I don’t understand how the code does that. Is the word “call” a pre-defined JavaScript function? In plain language, please explain “fn.call(object),” and explicitly tell me whether the object in parens (object) is the same object as the var object.
3). After the function has been assigned to the object, would you call that function by writing object.fn(); ?
var object = {};
function fn(){
return this;
}
assert( fn() == this, "The context is the global object." );
assert( fn.call(object) == object, "The context is changed to a specific object."
callis a function defined for aFunctionobject. The first parameter tocallis the object thatthisrefers to inside the function being called.When
fn()is called without any particular context,thisrefers to the global context, or thewindowobject in browser environments. Same rules apply for the value ofthisin the global scope. So infn() == this),thisrefers to the global object as well. However, when it is called in the context of some other object, as infn.call(object), thenthisinsidefnrefers toobject.fn.call(object)does not modify or assign anything toobjectat all. The only thing affected is thethisvalue insidefnonly for the duration of that call. So even after this call, you would continue callingfn()as regular, and not asobject.fn().The example simply demonstrates that the
thisvalue inside a function is dynamic.