javascript - Why did ECMAScript 5 add .bind()? - Stack Overflow

I just finished reading an article about ECMAScript 5 strict mode.It says that ECMAScript 5 added .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") ??

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

Share Improve this question edited Mar 9, 2012 at 15:20 kangax 39.2k13 gold badges100 silver badges135 bronze badges asked Mar 8, 2012 at 21:54 MoonMoon 22.6k72 gold badges198 silver badges276 bronze badges 1
  • 1 obj.method.bind(obj, "hello")() would be identical. – pimvdb Commented Mar 9, 2012 at 15:24
Add a ment  | 

2 Answers 2

Reset to default 12

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.

The main reason of creating a new function out of existing one is to be able to pass it together with the object on which it will be invoked. Consider this:

var obj = {
  x:"Hello",
  printPropX: function() {
    alert(this.x);
  }
};

setTimeout(obj.printPropX.bind(obj), 1000); // will alert "Hello" after 1 second

setTimeout(obj.printPropX, 1000); // will fail as 'this' won't be defined inside the function body once invoked

Although printPropX() is a member function of object 'obj', it won't be invoked with 'this' set to 'obj', unless bound with bind().

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745315150a4622183.html

相关推荐

  • javascript - Why did ECMAScript 5 add .bind()? - Stack Overflow

    I just finished reading an article about ECMAScript 5 strict mode.It says that ECMAScript 5 added .bind

    10小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信