Last Updated: February 25, 2016
·
616
· piatra

Using call and apply in javascript

You can execute functions in different contexts by taking advantage of call and apply methods in javascript. The best way to explain them is to show some code

var foo = function () {
    console.log('my name is ' + this.name)
};

obj1 = {
    name : 'Andrei'
}

We want to call function foo on that object so we do this

foo.call(obj1)

Which simply calls the function passing in a new context. The difference in the two methods, call and apply is the way we pass extra parameters to the foo function.
For call we would do

foo.call(obj1, bar, baz);

For apply we would do

foo.apply(obj1, [bar, baz]);

Real World
I found this tip very useful when working with jQuery. I am working on a javascript application with a lot of buttons that trigger different events. The problem is that this always refers to the button triggered but I am not interested in that, I want this to refer to the DOM element I am about to change.

$('#close').on('click', function(){
    // let's imagine $elem is a jQuery element
    // that changes depending on user actions
    fadeOut.call($elem);
})

My fadeOut function might be doing a lot of things like lowering the opacity over a period of time, changing the position of the element out of view and so on and it can be used on different elements without changing the code, only by changing the context.

var fadeOut = function () {
    // just an example
    this.toggleClass('fade-out');
}