The interviewer asked me this question in the interview and I didn't know how to answer it. Is the problem related to the this binding rule?
function sayName(){
console.log(this.name)
}
let a={
name:'name',
}
let b={
name:'NAME'
}
console.log(sayName.bind(a)()) // 'name'
console.log(sayName.bind(a).bind(b)()) // 'name'
function sayName() {
console.log(this.name);
}
let a = {
name: 'name',
};
let b = {
name: 'NAME',
};
const bindedSayName = sayName.bind(a);
/*Above: you have invoked a scoped-function available on Function prototype for all regular function, now the bindedSayName is no more a reference to sayName but rather its holding a bounded-function and what the bind those is to high-jack the sayName and pass the binded value to it passed in as an argument. Behind the hood its like this
Function.prototype._bind = function (thisRefObj) {
const parentFunc = this;
return function () {
parentFunc({ ...thisRefObj, author: 'Emmanuel Onah' });
};
};
*/
console.log(bindedSayName);
/*The console above returns a bounded function and not your sayName. So trying to bind another thing here will not get applied to your sayName function because its like trying to access a bind method from a bind function */
console.log(sayName.bind(a)()); // 'name'
console.log(sayName.bind(a).bind(b)()); /* Output is 'name': Note you r calling .bind(b) on ".bind(a) which is a bounded function on sayName". its like doing .then(res=>res).then(res=>res.json()), each .then() depends on the prevPromise. So your .bind(b) is not getting applied to sayName because you no more referencing to sayName. Just think of it from an object literal perspective*/
Also, you are able to call bind on another bind because bind is created using a regular function and a regular has a prototype of bind. So bind call bind because its a regular function.