开发者

Changing the context of a function in JavaScript

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜