Javascript Object Oriented Design - Javascript this Context








We can change this value to point to different context.

There are three function methods that can change the value of this.

The call() Method

call() function can change this context by running the function with a particular this value and specific parameters.

The first parameter of call() is the value to which this should be point to when the function is executed.

All subsequent parameters are the parameters that should be passed into the function.

For example, suppose you update writeLineForAll() to take a parameter:


function writeLineForAll(label) { /*from  w  ww  .jav a2s.c  o  m*/
    console.log(label + ":" + this.name); 
} 

var book1 = { 
    name : "Javascript" 
}; 

var book2 = { 
    name : "CSS" 
}; 

var name = "ABC"; 

writeLineForAll.call(this, "global");  
writeLineForAll.call(book1, "book1"); 
writeLineForAll.call(book2, "book2"); 

The code above generates the following result.

The first function call uses the global this and passes in the parameter "global".

By using call() method, we don't need to add the function directly onto each object.





The apply() Method

apply() method works the same as call() but it accepts only two parameters: the value for this and an array or array-like object of parameters to pass to the function.

We can use an arguments object as the second parameter with apply() method.


function writeLineForAll(label) { //w  w  w .  j  a  v  a  2s  .  c  o  m
    console.log(label + ":" + this.name); 
} 

var book1 = { 
    name : "Javascript" 
}; 

var book2 = { 
    name : "CSS" 
}; 

var name = "HTML"; 

writeLineForAll.apply(this, ["global"]);  
writeLineForAll.apply(book1, ["book1"]);  
writeLineForAll.apply(book2, ["book2"]);  

The code above generates the following result.





The bind() Method

The first argument to bind() is the this value for the new function.

All other arguments represent named parameters that should be set in the new function.

The following code shows two examples that use bind().

We create the writeLineForPerson1() function by binding the this value to book1, while writeLineForPerson2() binds this to book2 and binds the first parameter as "book2".


function writeLineForAll(label) { /* w  w w . ja v a 2  s .com*/
    console.log(label + ":" + this.name); 
} 

var book1 = { 
    name : "Javascript" 
}; 

var book2 = { 
    name : "CSS" 
}; 

// create a function just for book1 
var writeLineForPerson1 = writeLineForAll.bind(book1); 
writeLineForPerson1("book1");      

// create a function just for book2 
var writeLineForPerson2 = writeLineForAll.bind(book2, "book2"); 
writeLineForPerson2();             

// attaching a method to an object doesn't change 'this' 
book2.writeLine = writeLineForPerson1; 
book2.writeLine("book2");        

The code above generates the following result.