Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the context of a function in JavaScript

Tags:

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."
like image 307
mjmitche Avatar asked Mar 17 '11 03:03

mjmitche


People also ask

Is it possible to change functions context of execution?

If we want to, we can dynamically change the execution context of any method by using either call() or apply(). Both of these functions can be used to bind the "this" keyword to an explicit context.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

How can you call a function and assign the this context to an object?

call() and . apply() methods allow you to set the context for a function.

Can you reassign this in JavaScript?

In JavaScript, you can reassign values to variables you declared with let or var . I used to reassign values a lot.


1 Answers

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.

like image 104
Anurag Avatar answered Oct 17 '22 18:10

Anurag