Introduction to bind method in ECMAScript 5 (ES5) Memo

Source: Internet
Author: User

There has been a blurring of things about this, such as call, apply, and so on. This time see A and bind the pen question, therefore remember this article for forgetting.

Bind and call, as well as apply, are the one that can change the context. The difference is that call and apply are directly referenced on the method, and bind binds this to return a method, but the inner core is still apply.

See examples directly:

123456789101112 varobj = {  a: 1,  b: 2,  getCount: function(c, d) {    returnthis.a + this.b + c + d;  }};window.a = window.b = 0;console.log(obj.getCount(3, 4));  // 10varfunc = obj.getCount;console.log(func(3, 4));  // 7

Why is this so? Because the this in the context of Func is window! Bind exists precisely in order to change this point to get the desired value:

1234567891011 varobj = {  a: 1,  b: 2,  getCount: function(c, d) {    returnthis.a + this.b + c + d;  }};window.a = window.b = 0;varfunc = obj.getCount.bind(obj);console.log(func(3, 4));  // 10

Bind is a function extension method, bind code later rebind the func internal this point (obj), but not compatible with ie6~8, the following code is compatible:

12345678910111213141516171819 varobj = {  a: 1,  b: 2,  getCount: function(c, d) {    returnthis.a + this.b + c + d;  }};Function.prototype.bind = Function.prototype.bind || function(context) {  varthat = this;  return function() {    // console.log(arguments); // console [3,4] if ie<6-8>    returnthat.apply(context, arguments);  }}window.a = window.b = 0;varfunc = obj.getCount.bind(obj);console.log(func(3, 4));  // 10

In fact, it seems to me that the core of BIND is to return an uncommitted method if you use apply or call directly:

12 varans = obj.getCount.apply(obj, [3, 4]);console.log(ans); // 10

It is not possible to construct using the shorthand Func function, so passing this point with bind and returning an execution method is quite ingenious.

Introduction to bind method in ECMAScript 5 (ES5) Memo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.