美文网首页
JavaScript中call和apply的区别

JavaScript中call和apply的区别

作者: tonyzheng1 | 来源:发表于2016-08-14 22:34 被阅读54次
  1. call和apply的定义
  • call方法

    • 语法: call(thisObj[, arg1[, arg2[, ...[, argN]]]])
    • 定义: 调用一个对象的一个方法,以另一个对象替换当前对象
    • 说明: call方法可以用来代替另一个对象调用一个方法。call方法可将一个函数的对象上下文从初始的上下文改变为由thisObj指定的新对象。
  • apply方法

    • 语法: apply(thisObj, [, argArray])
    • 定义: 应用某一个对象的一个方法,用另一个对象替换当前对象
    • 说明: 如果argArray不是一个有效的数组或者不是一个arguments对象,那么将导致一个TypeError。如果没有提供argArray和thisObj任何一个参数,那么Global对象将被用作thisObj, 并且无法被传递任何参数。
  1. 代码示例
  • 基本使用

    function Animal(){    
      this.name = "Animal";    
      this.showName = function(){    
        alert(this.name);    
      }    
    }    
    
    function Cat(){    
      this.name = "Cat";    
    }    
    
    var animal = new Animal();    
    var cat = new Cat();    
    
    //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。    
    //输入结果为"Cat"    
    animal.showName.call(cat,","); //animal.showName.apply(cat,[]);  
    
  • 实现继承

    function Animal(name) {      
      this.name = name;      
      this.showName = function(){      
        alert(this.name);      
      }      
    }      
    
    function Cat(name) {    
      Animal.call(this, name);    
    }      
    
    var cat = new Cat("Black Cat");     
    cat.showName();
    

    Animal.call(this)的意思就是使用Cat对象代替this对象,那么Cat中就有Animal的所有属性和方法了。

  • 多重继承

    function Class10() {  
        this.showSub = function(a,b) {  
          alert(a-b);  
        }  
    }
    
    function Class11() {  
        this.showAdd = function(a,b) {  
          alert(a+b);  
        }  
    }  
    
    function Class2() {  
      Class10.call(this);  
      Class11.call(this);  
    }
    

    使用两个call就可以实现多重继承了。
    除了call,还有apply,这两个方法基本是一个意思,只是call的第二个参数可以是任意类型,但是apply的第二个参数必须是数组或者arguments。

相关文章

网友评论

      本文标题:JavaScript中call和apply的区别

      本文链接:https://www.haomeiwen.com/subject/agzysttx.html