Call and apply

suggest change

Functions have two built-in methods that allow the programmer to supply arguments and the this variable differently: call and apply.

This is useful, because functions that operate on one object (the object that they are a property of) can be repurposed to operate on another, compatible object. Additionally, arguments can be given in one shot as arrays, similar to the spread (...) operator in ES6.

const obj = {
    a: 1,
    b: 2,
    set: function (a, b) {
        this.a = a;
        this.b = b;
    }
};

obj.set(3, 7); // normal syntax
obj.set.call(obj, 3, 7); // equivalent to the above
obj.set.apply(obj, [3, 7]); // equivalent to the above; note that an array is used

console.log(obj); // { a: 3, b: 7 }

const myObj = {};
// myObj.set(5, 4); // TypeError: myObj has no set property
obj.set.call(myObj, 5, 4); // this inside set is myObj
obj.set.apply(myObj, [5, 4]); // same call, with the arguments in an array

console.log(myObj); // { a: 5, b: 4 }

ECMAScript 5 introduced another method called bind() in addition to call() and apply() to explicitly set this value of the function to specific object.

It behaves quite differently than the other two. The first argument to bind() is the this value for the new function. All other arguments represent named parameters that should be permanently set in the new function.

function showName(label) {
    console.log(label + ":" + this.name);
}
const student1 = {
     name: "Ravi"
};
const student2 = {
     name: "Vinod"
};

// create a function just for student1
const showNameStudent1 = showName.bind(student1);
showNameStudent1("student1"); // outputs "student1:Ravi"

// create a function just for student2
const showNameStudent2 = showName.bind(student2, "student2");
showNameStudent2(); // outputs "student2:Vinod"

// attaching a method to an object doesn't change `this` value of that method.
student2.sayName = showNameStudent1;
student2.sayName("student2"); // outputs "student2:Ravi"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents