Search code examples
javascriptcallbindecmascript-5

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") ??


Solution

  • 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.