Javascript call, apply, bind
Demystifying “this”
1 min readJun 3, 2020
The ability to use and manipulate “this” of function is key to good object-oriented programming in Javascript.
“this” is typically automatically assigned according to scope, but below 3 functions can change the value of “this”
- call
- apply
- bind
Important note:
“call” and “apply” execute a function. “bind” returns a function.
call
“call()” executes the function with a specific object to be used as “this” and specific parameters.
var num = 1;
var obj = {num: 100};
var addTothis = function(a, b) {
return this.num + a + b;
}
addTothis(100, 200); // 301
addTothis.call(obj, 100, 200); // 400
apply
The same concept as “call()” but pass the extra arguments as a list.
var num = 1;
var obj = {num: 100};
var addTothis = function(a, b) {
return this.num + a + b;
}
addTothis(100, 200); // 301// call
addTothis.call(obj, 100, 200); // 400// apply
var arr = [100, 200];
addTothis.apply(obj, arr); // 400
bind
“bind” just returns a function which uses the provided object for “this”.
var num = 1;
var obj = {num: 100};
var addTothis = function(a, b) {
return this.num + a + b;
}
addTothis(100, 200); // 301// call
addTothis.call(obj, 100, 200); // 400// apply
var arr = [100, 200];
addTothis.apply(obj, arr); // 400// bind
var boundedAddTothis = addTothis.bind(obj);
boundedAddTothis(100, 200); // 100 + 100 + 200 = 400// bind example with extra parameters
var boundedAddTothis2 = addTothis.bind(obj, 1, 2);
boundedAddTothis2(); // 100 + 1 + 2 = 103