A detailed description of the BIND function of the reading notes of the Advanced JavaScript program

Source: Internet
Author: User

Why BIND is required
 var  name =  " the window   "  var  object  = {name:   " my Object  "  , Getnamefunc:function () { return   F Unction () { return  this  .name; }}};alert ( object . Getnamefunc () ()); //  

Object.getnamefunc () returns an anonymous function that calls the function in the global environment, which refers to the global object

To solve this problem, you can save the this object in the external scope of the anonymous function in a variable that the closure can access, as follows

varName ="The Window";var Object={name:"My Object", Getnamefunc:function () {varthat = This; returnfunction () {returnThat.name; }}};alert (Object. Getnamefunc () ());//"My Object"

The above solution needs to modify the method of the object, if you cannot modify the method of the original object, how to do it?

At this point, we can use the Apply or call method to specify the scope of the function as follows

varName ="The Window";var Object={name:"My Object", Getnamefunc:function () {returnfunction () {return  This. Name; }    }};varFunc=Object. Getnamefunc (); Alert (Func.apply (Object));//"My Object"

With apply, call, you can already output the expected my Object

However, every call needs to be called as Func.apply (object), isn't it weird

The ideal way to call is, of course, after some sort of processing, which can then be called in Func (), like this

varName ="The Window";var Object={name:"My Object", Getnamefunc:function () {returnfunction () {return  This. Name; }    }};varFunc=Object. Getnamefunc (); Func=func.bind (Object); alert (func ()); //"My Object"
Bind in ECMAScript 5

ECMAScript 5 Fixed The Bind method, which creates a function instance whose this value is bound to the value passed to the BIND function, which gives a simple example of how the BIND function is used.

window.color="red"; var o={color:"blue"};function Saycolor () {    alert (this . color);} var func=saycolor.bind (o); func (); // "Blue"

Although this method is already available in most browsers for the ECMAScript 5 definition, you will still encounter compatibility issues with a few browsers that do not support it.

Using the Apply and call methods above, you can provide a solution like this

function.prototype.bind=function.prototype.bind| |     Function (context) {        var self=this;         return function ()        {            return  self.apply (context,arguments);        }    }
Bind in the Prototype.js
Function.prototype.bind =  Function () {   varThisobject =   Args.shift ();    return function () {     return fn.apply (object,       args.concat ( Array.prototype.slice.call (arguments));   }; };

In the above code,

Args=array.prototype.slice.call (arguments) will call the BIND function when the parameter collection arguments is converted to an array of arrays

Object=args.shift () pulls the first element of the args array as the current object

In the anonymous function, the call to Args.concat (Array.prototype.slice.call (arguments)) is to combine the arguments passed in when the anonymous function is called with the arguments that call bind when the parameters are combined into a single parameter array

See the above procedure in an invocation example

var ' prop x '  };
args = Array.prototype.slice.call (arguments) after args = [obj, 12, 23]
Object=args.shift (), args =[12, [], Object =obj

var A at
Boundexample (  arguments = 36, 49, call Args.concat (Array.prototype.slice.call (arguments)) After,arguments that our example () function receives = [A]
The bind in Firefox
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 ( Thisinstanceof Fnop &&Othis? This: Othis||window, Aargs.concat (Array.prototype.slice.call (arguments)));    }; Fnop.prototype= This. prototype; Fbound.prototype=NewFnop (); returnFbound; };}

Firefox provides a compatible implementation for BIND, and the main code is similar to the implementation in Prototype.js, and no longer explains

A detailed description of the BIND function of the reading notes of the Advanced JavaScript program

Related Article

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.