Use of call, apply, bind

Source: Internet
Author: User

Array Append

//splicing with Apply            vararr1=[12, ' Name:foo ', 2048]; vararr2=[' Joe ', ' Hello '];            Array.prototype.push.apply (ARR1,ARR2); Console.log (arr1);//(5) [Name:foo, 2048, "Joe", "Hello"]            //splicing with call            vararr1=[12, ' Name:foo ', 2048]; vararr2=[' Joe ', ' Hello '];            Array.prototype.push.call (ARR1,ARR2); Console.log (arr1);//(4) [Name:foo], 2048, Array (2)] Array (2) ["Joe", "Hello"] is arr2 only one, and then under the third place and 2 bits

Gets the maximum and minimum values in the array

// Compare call and apply (call when parameters are clear)            var numbers=[25,456,86,-45];             var maxnum=math.max.apply (math,numbers)// is an array            Console.log (maxnum) passed in;   456            var numbers=[25,456,86,-45];             var maxnum=math.max.call (math,25,456,86,-45)// incoming parameter            console.log (maxnum ); // 456

Verify that the array is not (provided that the ToString () method has not been rewritten)

var arr=[1,2,3,4,5];             function IsArray (obj) {                 return  Object.prototype.toString.call (obj) = = = ' [Object Array] ' ;            }            IsArray (arr);            Console.log (IsArray (arr))//true

Usage of apply

function log (msg)  //general notation            {                console.log (msg);            }            Log (1); // 1            Log (on); // 1 1

Using the Apply method

function log ()            {                console.log.apply (console,arguments);            }            Log (1); // 1            Log (on); // 1 2

Usage of BIND

//General wording
var
Foo ={bar:1, Eventbind:function() {Console.log ( This) var_this = This; $('. SomeClass '). On (' click ',function(event) {//Act on the eventConsole.log (_this.bar);//1 }); }} foo.eventbind ();          
 //bind 
var
foo = { Bar: 1 fu Nction () {$ ( '. SomeClass '). On (' click ', function // Act on the event Console.log (this . bar); // 1 }.bind (this

Bind () Creates a function that, when the Click event is bound to be invoked, its this keyword is set to the value passed in (this refers to the parameter passed in when bind () is called). So here we pass in the desired context this (actually foo), into the bind () function.
Then, when the callback function is executed, this points to the Foo object.

Case

varBar =function() {Console.log ( This. x); }            varFoo ={x:3            }            varsed ={x:4            }            varFunc =Bar.bind (foo). bind (SED); Func (); //3 At this point the output is 3                            varFIV ={x:5            }            varFunc =Bar.bind (foo). bind (SED). bind (FIV); Func (); //3//At this time the output is 3

In JavaScript, multiple bind () is not valid. For a deeper reason, the implementation of BIND () is equivalent to using a function to wrap a call/apply inside, and the second bind () is equivalent to wrapping the first bind (), so the second bind is not valid.
What the Bind () returns

  var  obj = {x:  81,};  var  foo = {getX:  function   () { return  this  .x; }}  var  a = Foo.getX.bind (obj); // 81  Console.log (A ()); // 81  //  Console.log (Foo.getX.bind (obj)),//81 call and apply are executed immediately, and bind returns the function  

Call method

            //To invoke an anonymous function by using the call method            varpeoples=[{name:' Jane ', age:16}, {name:' Maria ', age:15}            ]             for(vari=0;i<peoples.length;i++){                (function(i) { This. print=function() {Console.log (i+"----" + This. name+ "---" + This. Age); }                     This. Print (); }). Call (Peoples[i],i)}
//calling the parent constructor using the call method            functionProduct (name,price) { This. name=name;  This. price= Priceif(Price < 0){                        ThrowRangeerror (' connot create product ' + This. name+ ' with a negative price '); }                }                    functionFood (Name,price) {Product.call ( This, Name,price);  This. category= ' food '; }                varCheese =NewFood (' feta ', 5); Console.log (cheese);//Food {name: ' feta ', price:5, Category: ' Food '}

Simple usage

function Cat () {                }                cat.prototype={food                     :"Fish",                     say:function() {                           alert ("I Love" +this);                     }                }                              var New Cat;                Blackcat.say ();                 var whitedog = {food: "Bone"};                Console.log (Whitedog);                BlackCat.say.apply (Whitedog);

Summarize:

Apply, call, and bind are all pointers to the This object that is used to change the function;
Apply, call, bind the first parameter is the object that this is to point to, that is, the context you want to specify;
Apply, call, bind three can use the following parameters to pass the parameter;

Apply, call will execute immediately, and bind's callback function

Apply is passed in an array of apply (This,[argu1,argu2,argu3,argu4]), call is Call (THIS,ARGU1,ARGU2,ARGU3,ARGU4), if the number of arguments passed in is known, You can use the call method. If the number is unknown, use the Apply method.




Use of call, apply, 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.