JavaScript function Method-bind ()

Source: Internet
Author: User
Tags function prototype

Function.prototype.bind ()

ECMAScript5, but the ECMASCRIPT3 can be emulated to implement its method.

Role:

  The bind () method creates a new function, and when the new function is called, its this value is the first parameter passed to bind (), and its arguments are the other parameters of bind () and its original parameters.

Basic syntax

Fun.bind (thisarg[, arg1[, arg2[, ...])

/**
* For a given function, creates a bound function, which has the same body as the original function.
* The This object of the bound function was associated with the specified object, and have the specified initial parameters.
* @param thisarg an object to which the This keyword can refer inside the new function.
* @param argarray A List of arguments to being passed to the new function.
*/
Bind (Thisarg:any, ... argarray:any[]): any;

Parameters

  thisArg

When a binding function is called, the parameter is pointed to when the original function runs. newThis parameter is not valid when the binding function is invoked using an operator.

  arg1, arg2, ...

When a binding function is called, these parameters, together with the parameters of the binding function itself, are ordered as arguments to the original function when it is run.

return value

Returns a copy of the original function modified by the specified this value and initialization parameters

Describe:

    1. The bind () function creates a new function (called a binding function), and the new function has the same function body as the modulated function (the target function of the bound function).
    2. This value is bound to the first parameter of bind () when the target function is called, and the parameter cannot be overridden.
    3. When a binding function is called, bind () also accepts a preset argument to the original function.
    4. A binding function can also use new operators to create objects: This behavior is like using the original function as a constructor. The supplied this value is ignored, while the parameter at the time of invocation is supplied to the impersonation function.

The first step is to understand several concepts, binding functions, Target functions

Let's look at the following example:

var  function () {         Console.log (this. Y);     }; var o = {x:1, y:2 }; var bindfun = origin.bind (o); Bindfun ();

Origin objective function (original function) The Bindfun binding function understands the objects that these functions refer to. Then one by one to see the meaning of each of the words described;

The <1> binding function has the same method body as the target function;

   

var function () {    console.log ("12345");}; var succ = sum.bind (); sum ();//12345succ ();//12345

As you can see from the printed results above, it is true to verify that they have the same method body.

<2> when the target function is called, its this is bound to the first argument of the bind () function, which cannot be overridden

  

var function () {    Console.log (this. y);}; var succ = Sum.bind ({x:1, Y:2 }); succ ();//1 2

When the <3> binding function is called, bind () also accepts the default parameters provided to the original function

var function (z) {    console.log (this. Y, z);}; var succ = Sum.bind ({x:1, y:2}, 3); succ ();//1 2 3

<4> A binding function can also use the new operator to create an object: This behavior is like using the original function as a constructor. The supplied this value is ignored, while the parameter at the time of invocation is supplied to the impersonation function.

var function (z) {    console.log (this. Y, z);}; var succ = Sum.bind ({x:1, y:2}, 3); new succ (); Undefined undefined 3

How to simulate the bind () function effect in ECMASCRIPT3

if(!Function.prototype.bind) {Function.prototype.bind=function(O/*, org*/ ) {        varSelf = This, Boundargs=arguments; return function() {            //creates an argument list that passes the second and subsequent arguments passed in to bind () to the function            varargs =[], I;  for(i = 1; i < boundargs.length; i++) Args.push (Boundargs[i]);  for(i = 0; i < arguments.length; i++) Args.push (Arguments[i]); returnself.apply (o, args);    }; };}

Compatibility with old browser mode

  bind The function was added to the fifth version of ECMA-262; it may not run on all browsers. You can make it work by adding the following code partially at the beginning of the script, allowing the unsupported browser to use the bind() feature as well.

if(!Function.prototype.bind) {Function.prototype.bind=function(othis) {if(typeof  This!== "function") {            Throw NewTypeError ("Function.prototype.bind-what is trying to be bound are not callable"); }        varAargs = Array.prototype.slice.call (arguments, 1),//Get ParametersFtobind = This,//Save External thisFnop =function() {},//used primarily to determine whether an instance of a functionFbound =function() {                returnFtobind.apply ( This instanceofFnop?//prevent call apply mode invocation                     This: Othis|| This,//From here you can see that othis is optional when not passed, the default is the current context objectAargs.concat (Array.prototype.slice.call (arguments)));        }; Fnop.prototype= This. prototype;//Keep with objective function alwaysFbound.prototype =NewFnop ();//Assigning a value to a binding function prototype        returnFbound; };}

JavaScript Function Method-bind ()

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.