javaScript中call()理解


obj1.method1.call(obj2,arg1,arg2) 

call的作用就是把obj1的方法放到obj2上使用,后面的arg1..这些做为参数传入

例:

  1. function add(a,b)  
  2. {  
  3.     alert(a+b);  
  4. }  
  5. function sub(a,b)  
  6. {  
  7.     alert(a-b);  
  8. }  
  9.   
  10. add.call(sub,3,1);   

    这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4); 

// 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。 

例:

  1. function Animal(){    
  2.     this.name = "Animal";    
  3.     this.showName = function(){    
  4.         alert(this.name);    
  5.     }    
  6. }    
  7.   
  8. function Cat(){    
  9.     this.name = "Cat";    
  10. }    
  11.    
  12. var animal = new Animal();    
  13. var cat = new Cat();    
  14.     
  15. //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。      
  16. animal.showName.call(cat);  //输入结果为"Cat"    
  17. //animal.showName.apply(cat,[]);  
例 实现继承

  1. function Animal(name){      
  2.     this.name = name;      
  3.     this.showName = function(){      
  4.         alert(this.name);      
  5.     }      
  6. }      
  7.     
  8. function Cat(name){    
  9.     Animal.call(this, name);    
  10. }      
  11.     
  12. var cat = new Cat("Black Cat");     
  13. cat.showName(); 

cat类继承Animal类, Animal.call(this, name); 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法,Cat对象就能够直接调用Animal的方法以及属性了.

例:多重继承

  1. function Class10()  
  2. {  
  3.     this.showSub = function(a,b)  
  4.     {  
  5.         return(a-b);  
  6.     }  
  7. }  
  8.   
  9. function Class11()  
  10. {  
  11.     this.showAdd = function(a,b)  
  12.     {  
  13.         return(a+b);  
  14.     }  
  15. }  
  16.   
  17. function Class2()  
  18. {  
  19.     Class10.call(this);  
  20.     Class11.call(this);  
  21. }
  22. var test=new Class2();
  23. console.log(test.showSub(29,17));
  24. console.log(test.showAdd(29,17));
说了call ,当然还有 apply,这两个方法基本上是一个意思,区别在于 call 的第二个参数可以是任意类型,而apply的第二个参数必须是数组,也可以是arguments
还有 callee,caller..


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值