call-apply-bind
by Shridhar Baddur
JavaScript
//call, apply and bind lets you borrow functionalities(functions) from other objects. so that we can do cool mixins, multiple inheritence. Borrow function prototype to another.
/* Short explanation
var obj = {
prop: value;
};
var funcName = function(arg1, arg2, arg3) {
}
funcName.call(obj, arg1, arg2, arg3);
funcName.apply(obj, [arg1, arg2, arg3]);
var bound = funcName.bind(obj);
bound(arg1, arg2, arg3); */
//call example
let add = function(c) {
console.log(this.a + this.b + c);
}
let obj = {
a: 1,
b: 2
};
add.call(obj, 3); //funcName.call(objName, funcArg)
//example 2
let argsToArray = function() {
console.log([].slice.call(arguments))
}
argsToArray(1, 2, 3);
//example 3
let mammal = function(legs) {
this.legs = legs;
}
let cat = function(legs, isDomesticated) {
mammal.call(this, legs);
this.isDomesticated = isDomesticated;
}
let lion = new cat(4, false);
console.log(lion);
//apply examples
let numArray = [1, 2, 3];
console.log(Math.min.apply(null, numArray));
//bind examples
let obj1 = {
num: 2
};
let addToThis = function(a, b, c) {
return this.num + a + b + c;
};
let boundAdd = addToThis.bind(obj1);
console.log(boundAdd(1, 2, 3));