Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did ECMAScript 5 add .bind()?

I just finished reading an article about ECMAScript 5 strict mode.

It says that ECMAScript 5 added .bind().

var obj = {
  method: function(name){
    this.name = name;
  }
};

obj.method.bind(obj,"hello");

Isn't it identical to obj.method.call(obj,"hello") ??

like image 771
Moon Avatar asked Feb 20 '26 22:02

Moon


1 Answers

No, it's not identical.

With bind you're producing a function, without calling anything. With call — as in your obj.method.call(obj, 'hello') — you're actually calling a method.

An "identical" expression to obj.method.bind(obj, 'hello') would be function(){obj.method.call(obj, 'hello')}. That's more cruft. And that's the cruft ES5 is trying to provide convenience for.

There are also historical reasons for introduction of bind; it first became popular as one of the helper methods in Prototype.js few years ago. Then made its way to other popular libraries, such as underscore.js. ES5 just followed what was already popular and in demand.

like image 57
kangax Avatar answered Feb 22 '26 11:02

kangax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!