9

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."

1 Answer 1

10

call is a function defined for a Function object. The first parameter to call is the object that this refers to inside the function being called.

When fn() is called without any particular context, this refers to the global context, or the window object in browser environments. Same rules apply for the value of this in the global scope. So in fn() == this), this refers to the global object as well. However, when it is called in the context of some other object, as in fn.call(object), then this inside fn refers to object.

fn.call(object) does not modify or assign anything to object at all. The only thing affected is the this value inside fn only for the duration of that call. So even after this call, you would continue calling fn() as regular, and not as object.fn().

The example simply demonstrates that the this value inside a function is dynamic.

Sign up to request clarification or add additional context in comments.

2 Comments

regarding the first paragraph in your answer (i.e. call and object), is that always the case or just with this specific code? thank you very much for your help.
When a function is invoked with call or apply, the first parameter will always determines the this value inside that function. That is always the case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.