Saturday, June 16, 2018

JavaScript - Object - this - bind, call, apply

The below code demonstrates the usage of the following object methods:
  • bind
  • call
  • apply

// here this refers to the window object
function myFunc(message){
  console.log(message+" "+this);
}


var obj = {
  objectFunction:myFunc
};

var Person = {
  name: "Cassandra",
  age: 27
}

// Observe the extra paranthesis in Bind
obj.objectFunction.bind(Person,"Bind says - Hey there ")(); 
// Observe that there are no extra paranthesis
obj.objectFunction.call(Person,"Call says - Hey there ");
// In apply parameters are passed using an array
obj.objectFunction.apply(Person,["Apply says - Hey there "]);




Refer:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Practice at:
http://jsbin.com

No comments:

Post a Comment