首页 > 代码库 > js call()方法

js call()方法

 1 //用add方法替换sub方法 2 function add(a,b){ 3   console.log(a+b) 4 } 5 function sub(a,b){ 6   console.log(a-b) 7 } 8 add.call(sub,3,1); 9 10 //c1的方法放到c2上执行11 function Class1(){12   this.cName = ‘class1‘;13   this.showClass = function(){14     console.log(this.cName)15   }16 }17 function Class2(){18   this.cName = ‘class2‘;19 }20 var c1 = new Class1();21 var c2 = new Class2();22 c1.showClass.call(c2);23 24 //实现继承 用Class3对象代替Class4的this对象,Class4即拥有所有Class3的属性和方法25 function Class3(){26   this.showTxt = function(txt){27     console.log(txt)28   }29 }30 function Class4(){31   Class3.call(this)32 }33 var c4 = new Class4();34 c4.showTxt(‘hello‘);35 36 //多重继承37 function Add() {38   this.showAdd = function(a, b) {39     console.log(a+b)40   }41 }42 function Sub() {43   this.showSub = function(a, b) {44     console.log(a-b)45   }46 }47 function Count(){48   Add.call(this);49   Sub.call(this);50 }51 var c = new Count();52 c.showAdd(1,3);53 c.showSub(1,3);

 

js call()方法