Getting back up to speed with NodeJS, Part1
Part 1: call, apply and bind
Lately I have been doing some more coding again with NodeJS or maybe better to say Javascript :)
I will be adding some short items about things so that I dont forget and maybe also can help others with explaining what specific functions do.
Today we start with call
, apply
and bind
. To explain the differences I have created some small code which should explain it all in a simple way:
var obj = { num:2 };
var functionName = function(arg1, arg2, arg3){
return obj.num + arg1 + arg2 + arg3;
};
// call a object with an outside function
console.log('call: ' , functionName.call(obj, 1,2,3));
// call a object with an outside function, same but with an array as arguments
console.log('apply: ', functionName.apply(obj, [1,2,3]));
// call a new object with a merged function inside
var bound = functionName.bind(obj);
console.log('bound: ' , bound(1,2,3));
As you can see, call
& apply
are almost the same. bound
clearly has a different use-case.