How to use the functions of apply and call

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

Although  apply and  call  can implement same function. However, there is a litter different between them. Please pay attention to look at the examples below:

 

Define an object Person

 

1 Person=function(name,age){2    this.name=name;3    this.age=age;7 }8 9 var pin=new Person("Pin",26); //create an object

 

After that, we need to define some functions (skating,running,eating) with different parameters respectively.

 1 function skating() // It don‘t need any parameter 2 { 3    alert(this.name+" like skating!"); 4 } 5  6 function running(distance) // It need 1 parameter 7 { 8    alert(this.name+" can only run "+distance+" meters!"); 9 }10 11 function eating(fruit1,fruit2) // It need 2 paramters12 {13    alert(this.name+" like eating "+fruit1+" and "+fruit2+"!");14 }

 

Now, I‘ll use apply and call respectively.

//after using applyskating.apply(pin); running.apply(pin,[1000]);eating.apply(pin,["apple","orange"]);Results respectively:Pin like skating!Pin can only run 1000 meters!Pin like eating apply and orange!

 

//after using callskating.call(pin); running.call(pin,1000);eating.call(pin,"apple","orange");Results respectively:Pin like skating!Pin can only run 1000 meters!Pin like eating apply and orange!

From the results above, we can know the differences between apply and call :

Same:

1. apply and call all can make object pin implement sakting, running and eating, respectively. Exactly, object pin own three new functions (sakting, running and eating).

2. The first parameter pin is the replace the key this among three functions. So, when the three functions call the variable this.name, the key this is NOT three functions themselves but object pin.

3. If the first paramter is null, the global object window will replace it.

4. If the function (such as skating) don‘t need any paramters, the apply and call are same.

 

Difference:

If the function need a parameter at least, the parameter should be a array using apply. For the call, without any constraints.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.