Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why two bindings to the same function return different values

Tags:

javascript

When binding a function to the same context, the resulting reference is different every time.

function foobar() {
    return 1;
}

var foo = foobar.bind(this);
var bar = foobar.bind(this);

console.log(foo === bar); // Nope
  1. Does that code copy the function every time?
  2. Wouldn't there be any benefit in caching that behavior?
  3. Is it implementation specific?
  4. Or is it specified somewhere in ecmascript specification?
like image 788
Misiur Avatar asked Dec 14 '15 20:12

Misiur


2 Answers

Yes the Function.prototype.bind() creates a new function every time.

like image 82
madox2 Avatar answered Oct 22 '22 06:10

madox2


Does that code copy the function every time?

Whether or not it copies the original function is an implementation detail of the underlying JS engine.

The return value of bind is a new function, and you'll get a new one each time you call bind.

Wouldn't there be any benefit in caching that behavior?

There might be a mild performance gain to be had in caching the resulting function, but probably not enough to worry about unless you are generating hundreds of bound copies of the same function. Beware of premature optimization.

like image 2
Quentin Avatar answered Oct 22 '22 07:10

Quentin