Javascripts bind, call and apply

Posted By : Arun Kumar | 01-Nov-2015

Javascripts bind

Javascript functions has some in-built methods and few of them are bind() ,call() and apply().
the bind method creates a new copy of the function in the memory space and sets the "this" object to the object passed in but doesn't executes the function.While call and apply methods executes the function after setting the "this" object to the object passed in but doesn't creates a new copy.

example:
//let's create a variable first
var value = {
    greet:"hi!"
};
//and the function
function myFunction(){
    console.log(this.greet);
}
Notice the this.value inside the function is going to look inside the function object for a value.If it is'nt there then it is going to look out for it on the global scope.So it is going to return a undefined value.
But we can set its value by binding an object to it by simply calling bind() method to this function.

//bind object
var runthis = myFunction.bind(value);

//Now lets run
runthis();

//output
hi!


we can also use the call() method by
var runthis = myFunction.call();

and this is going to output the same result.

and the apply() method works the same way as the call() method but it takes other parameters in the array format if the function requires the parameters.

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..