Understand the Function.prototype.bind in JavaScript

Source: Internet
Author: User

function bindings are probably the least bit of a concern when you start using JavaScript, but when you realize that you need a solution to solve how to keep the this context in another function, what you really need is Function.prototype.bind (), but you may still not be aware of this.

The first time you encounter this problem, you may prefer to set this to a variable so that you can continue referencing it after changing the context. Many people choose to use Self, _this or context as the variable name (and others use that). These methods are useful and of course there is no problem. But there is a better, more dedicated way.

What is the problem we really need to solve?

In the example code below, we can justifiably cache the context into a variable:

1 varMYOBJ = {2  3Specialfunction:function () {4  5     },6  7Anotherspecialfunction:function () {8  9     },Ten   OneGetasyncdata:function(CB) { A CB (); -     }, -   theRenderfunction () { -         varthat = This; -          This. Getasyncdata (function () { - that.specialfunction (); + that.anotherspecialfunction (); -         }); +     } A }; at   -Myobj.render ();

If we simply use This.specialfunction () to invoke the method, we will find that the program has an error.

We need to keep a reference to the MYOBJ object context for the execution of the callback function. Calling That.specialfunction () allows us to maintain the scope context and execute our functions properly.

However the use of Function.prototype.bind () can have a more concise and clean way:

1Renderfunction () {2  3      This. Getasyncdata (function () {4  5          This. Specialfunction ();6  7          This. Anotherspecialfunction ();8  9}.bind ( This));Ten   One}
What did we just do?

. Bind () Creates a function that, when called, the This keyword is set to the value passed in (this refers to the parameter passed in when bind () is called).

So we pass in the desired context, this (which is actually MYOBJ), into the. bind () function.

Then, when the callback function is executed, this points to the MYOBJ object.

Browser support Support
Browser Version
Chrome 7
Firefox (Gecko) 4.0 (2)
Internet Explorer 9
Opera 11.60
Safari 5.1.4

As you can see, unfortunately, Function.prototype.bind is not supported in the IE8 and below, so if you do not have a fallback option, you may run into problems.

if(!Function.prototype.bind) {Function.prototype.bind=function(othis) {if(typeof  This!== "function") {      //closest thing possible to the ECMAScript 5 internal iscallable function      Throw NewTypeError (" Function.prototype.bind-what are trying to be bound are not callable"); }     varAargs = Array.prototype.slice.call (arguments, 1), Ftobind= This, Fnop=function() {}, Fbound=function () {          returnFtobind.apply ( This instanceofFnop &&Amp;amp; Othis? This: Othis, Aargs.concat (Array.prototype.slice.call (argume        (NTS)));     }; Fnop.prototype= This. prototype; Fbound.prototype=NewFnop (); returnFbound; };}

Understand the Function.prototype.bind in JavaScript

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.