Javascript apply, call, bind

Last modified: 
Thursday, April 6th, 2017
Topics: 
Javascript

Apply, Call, Bind

Both call and apply execute the lefthand function as though it were a member of the context, where lefthandFunction.call(context, args...). The only difference is call takes comma separated args, and apply accepts an array.

var a = { age: 20 };
var b = { age: 30 };

function multiplyAddDivide(i, j, k) {
  return (this.age * i + j) / k; 
}

var callA = multiplyAddDivide.call(a, 2, 5, 5); 
console.log(callA); // 9

var callB = multiplyAddDivide.call(b, 2, 5, 5); 
console.log(callB); // 13

var applyA = multiplyAddDivide.apply(a, [2, 5, 5]);
console.log(applyA); // 9

var applyB = multiplyAddDivide.apply(b, [2, 5, 5]);
console.log(applyB); // 13

Bind is similar to call, but it returns a function bound to the context where lefthandFunction.bind(context).

var boundMultiplyAddDivideA = multiplyAddDivide.bind(a);
console.log(boundMultiplyAddDivideA(2, 5, 5)); // 9

var boundMultiplyAddDivideB = multiplyAddDivide.bind(b);
console.log(boundMultiplyAddDivideB(2, 5, 5)); // 13

JS Bin on jsbin.com


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.