Js apply和call 實現繼承


Function.apply:
Function.apply(obj,args)方法能接收兩個參數,
obj:這個對象將代替Function類里this對象,
args:這個是數組,它將作為參數傳給Function(args-->arguments).
 
Function.call:
Function.call(obj,[param1[,param2[,…[,paramN]]]]),
obj:這個對象將代替Function類里this對象,
params:這個是一個參數列表.
 
call和apply一樣,只是參數列表不同而已.
 
Person類:
function Person(name,age) {
  this.name = name;
  this.age = age;
}
Student類:
function Student(name,age,height) {
  Person.apply(this,arguments);
  //Person.call(this,name,age,height);   //call方法的傳參方式;    
  this.height = height;
}
實例化:
var student = new Student("chams",22,"173");
測試:
console.log("name:" + student.name + "  age:" + student.age + "  height:" + student.height);

 

Student類中並沒有name和age屬性,但是通過apply和call的繼承,使Student類繼承了Person類中的成員方法.

 

有關Apply的妙用:

1、輸出數組中最大的元素:

var arrs = [1,70,9,180,19,25,100,2,20];
function maxArrs(arrs){
  return Math.max.apply('',arrs);
}
//console.log(Math.max(arrs));    //不能直接Math.max(數組變量),只能Math.max(1,70,9,180,19,25,100,2,20);否則輸出NaN;
console.log(maxArrs(arrs));

 

2、數組的push方法:

var arrs1=[5,1,3],arrs2=[3,1,5];
Array.prototype.push.apply(arrs1,arrs2);  //[5, 1, 3, 3, 1, 5]
//arrs1.push(arrs2);    //[5, 1, 3, [3, 1, 5]]
console.log(arrs1);

 

如果用arrs1.push(arrs2),輸出的是[5,1,3,[3,1,5]],這樣是把arrs2整個數組當成一個元素添加到arrs1,而不是依次添加.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM