JS's call Apply Bind method

Source: Internet
Author: User

JS's call apply Bind method is common in order to change the execution environment of a method (context)

Pager

Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Thisobj
Options are available. The object that will be used as the current object.
Arg1, Arg2, ArgN.
Options are available. The method parameter sequence will be passed.

If strict mode "use strict" is not set

 When thisobj does not exist or is undefined or null or is this, it implicitly points to the Global Object (window in the browser)

The second parameter is a value

Apply

Apply ([Thisobj[,arg1, Arg2, ArgN])

Apply and call, the difference is just the second parameter, which is the form of an array (or an array of classes)

Bind

Bind (Thisarg [, Arg1 [, arg2, ...]);

Bind also changes the execution environment of a method, the difference is also the second parameter (also a Parameter form) and "return value" characteristics.

It binds a Func to the context of the Thisarg, passes in the corresponding parameter, and returns it as a new function for invocation.

such as Func.call (FUNC1,VAR1,VAR2,VAR3)

The corresponding apply wording is: func.apply (Func1,[var1,var2,var3])

The corresponding bind notation is: Func.bind (FUNC1,VAR1,VAR2,VAR3) ()

To raise a chestnut:

// ' use strict ' var name = ' name1 '; var obj = {    ' name2 ',    function(STR1,STR2) {        = str1 | | ";         = STR2 | | ";         this. Name + str2);    }};o Bj.sayname (); Obj.sayName.bind (window,' Hello: ', '! ') ) (); Obj.sayName.apply (This, [' Hello: ', ', ']); Obj.sayName.call (obj,' Hello: ', '. ');

The output will be:

Note 1: Bind is supported for IE9 (including IE9)

So, on a browser that doesn't support bind, we need to simulate

function (context) {    varThis,                //  gets to bind the second parameter (all parameters in)        args = Array.prototype.slice.call (arguments,1);         // returns a new function    return function () {        // assign the relevant parameters to this bind method and assign the environment to the context        return  Self.apply (Context,args);     };

NOTE 2:

Function.prototype's apply and call were added in the ECMA262 Edition3 released in 1999 (1998 release ECMA262 Edition2).

Prior browsers such as IE5.01 (JScript 5.0) are not apply and call. Therefore, there are some compatibility issues. So

Simulation of Call:

Function.prototype.Call =function(context) {//First judge The given context, that is, the first parameter of callContext = (context = = undefined)?Window:context; vartemp =[], Evalstr= ' '; //Finally, an eval string function call form is formed for dynamic execution     for(varI=1,j=arguments.length; i<j; i++) {Temp.push (' arguments[' + i + '] '); }        //add a new method to the context (with this value)Context._apply = This; Evalstr= ' context._apply (' + temp.join (', ') + ') '; //Console.log (EVALSTR);    Try{               //executing a function calleval (EVALSTR); }Catch(e) {Throw NewError (e.message); }finally{               //Destroy this property        Deleteobj._apply; }};

Impersonation of Apply:

Apply is also similar, because the second parameter is the form of an array of classes, so you also want to transform the arrays

//the second parameter, args, is for ease of useFunction.prototype.Apply =function(Context,args) {context= (Context = = undefined)?Window:context; vartemp =[], Evalstr= ' '; //directly take the elements of the second parameter array and then combine the join (', ')        //why not just use arguments[1]?         //because the join also uses Array.prototype.join.call at this point, call does not necessarily support     for(varI=0,j=args.length; i<j; i++) {Temp.push (' args[' + i + '] '); } context._apply= This; Evalstr= ' context._apply (' + temp.join (', ') + ') '; //Console.log (EVALSTR);    Try{eval (evalstr); }Catch(e) {Throw NewError (e.message); }finally{        Deleteobj._apply; }};

OK look at the contrast effect

Function.prototype.Bind =function(context) {varSelf = This, args= Array.prototype.slice.call (arguments,1); return function(){        returnself.apply (Context,args); };}; Function.prototype.Call=function(context) {context= (Context = = undefined)?Window:context; vartemp =[], Evalstr= ' ';  for(varI=1,j=arguments.length; i<j; i++) {Temp.push (' arguments[' + i + '] '); } context._apply= This; Evalstr= ' context._apply (' + temp.join (', ') + ') ';    Console.log (EVALSTR); Try{eval (evalstr); }Catch(e) {Throw NewError (e.message); }finally{        Deleteobj._apply; }}; Function.prototype.Apply=function(Context,args) {context= (Context = = undefined)?Window:context; vartemp =[], Evalstr= ' ';  for(varI=0,j=args.length; i<j; i++) {Temp.push (' args[' + i + '] '); } context._apply= This; Evalstr= ' context._apply (' + temp.join (', ') + ') ';    Console.log (EVALSTR); Try{eval (evalstr); }Catch(e) {Throw NewError (e.message); }finally{        Deleteobj._apply; }};varname = ' Name1 ';varobj ={name:' Name2 ', Sayname:function(STR1,STR2) {str1= STR1 | | ‘‘; STR2= STR2 | | ‘‘; Console.log (str1+ This. Name +str2); }};obj.sayname (); Obj.sayName.bind (window,' Hello: ', '! ') (); Obj.sayName.Bind (window,' Hello: ', '! ') (); Obj.sayName.apply ( This, [' Hello: ', ', ']); Obj.sayName.Apply ( This, [' Hello: ', ', ']); Obj.sayName.call (obj,' Hello: ', '. '); Obj.sayName.Call (obj,' Hello: ', '. ');

JS's call Apply Bind method

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.