美文网首页
[读] JS中的call()和apply()方法

[读] JS中的call()和apply()方法

作者: 不系流年系乾坤 | 来源:发表于2017-09-20 16:28 被阅读1次

JS中的call()和apply()方法

function add(a,b)  
{  
    alert(a+b);  
}  
function sub(a,b)  
{  
    alert(a-b);  
}  
  
add.call(sub,3,1); //4
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(); 
  • 多重继承
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);  
}  

相关文章

网友评论

      本文标题:[读] JS中的call()和apply()方法

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