zoukankan      html  css  js  c++  java
  • How to use the functions of apply and call

    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 paramters
    12 {
    13    alert(this.name+" like eating "+fruit1+" and "+fruit2+"!");
    14 }

    Now, I'll use apply and call respectively.

    //after using apply
    skating.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 call
    skating.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 (saktingrunning 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.

  • 相关阅读:
    有点郁闷,但是又不能表现出来,好难过
    搞平衡,我们公司跟国企也没有啥区别
    找兼职遇到的尴尬
    两岁的儿子
    Shark DB Expert 2.6数据库客户端工具终结者 问世
    .Net 中访问Oracle 数据表,出现OCI22053: overflow error
    Oracle冷备迁移过程和在线日志损坏处理
    转:Oracle数据库的优化之数据库磁盘I/O
    Linux批量移动文件grep+mv
    Oracle下导入txt的shell脚本以及配置
  • 原文地址:https://www.cnblogs.com/pinxiong/p/3774864.html
Copyright © 2011-2022 走看看