DEV Community

Discussion on: Function.bind.bind does not work in JavaScript

Collapse
 
davutkara profile image
Davut KARA

When you use bind it does not run your function just it sets the data 5,

So, printThis.bind(5) set 5 to 'this' then it does not return the exact function becuse it returns prototype undefined.

const l = printThis.bind(5).prototype
console.log(l) // undefined

So you cannot use again, you can think like a constant variable, it's set one time then you can not set again.

As a result, I write a function rbind means 're bind'.
It simply run the function first then returns the function which is not changed.

Function.prototype.rbind = function (o){
  this.bind(o)() // set and call
  return this;
}

function printThis() {
   console.log(this);
   return this
}

const f = printThis.rbind(5).rbind(7);
f(); // prints 5, 7

f.call(9); // prints 9
Collapse
 
akashkava profile image
Akash Kava

That is interesting, I can check if prototype is undefined, that means function is already bound.

Collapse
 
dexygen profile image
George Jempty

No it doesn't mean that necessarily. Somebody could explicitly set the prototype to undefined for instance.

Thread Thread
 
anduser96 profile image
Andrei Gatej • Edited

So if .prototype is already undefined it means that the function cannot be chained, right?