不少讀者關於js opp的繼承比較模糊,本文總結了oop中的三種繼承方法,以助於讀者進行區分。數組
<繼承使用一個子類繼承另外一個父類,子類能夠自動擁有父類的屬性和方法。(繼承的兩方,發生在兩個類之間)>
app
1、經過object實現繼承函數
1:定義父類
function Parent(){}
2:定義子類
funtion Son(){}
3:經過原型給Object對象添加一個擴展方法。
Object.prototype.customExtend = function(parObj){
for(var i in parObj){
// 經過for-in循環,把父類的全部屬性方法,賦值給本身
this[i] = parObj[i];
}
}
4:子類對象調用擴展方法
Son.customExtend(Parent);oop
1 // 1.定義父類 2 function Person(name,age){ 3 this.name = name; 4 this.age = age; 5 this.say = function(){ 6 alert(this.name+":"+this.age); 7 } 8 } 9 // 2.定義子類 10 function Student(no){ 11 this.no = no; 12 this.add = function(a,b){ 13 alert(a+b); 14 } 15 } 16 function Programmer(lang){ 17 this.lang = lang; 18 this.codding = function(){ 19 alert("我愛敲代碼!敲代碼使我快樂!"); 20 } 21 } 22 // 3.經過原型給Object對象添加一個擴展方法。 23 Object.prototype.customExtend = function(parObj){ 24 for(var i in parObj){ 25 // 經過for-in循環,把父類的全部屬性方法,賦值給本身 26 this[i] = parObj[i]; 27 } 28 } 29 30 var p = new Person("小明","18"); 31 var s = new Student("0001"); 32 s.customExtend(p);//如今s繼承了p的全部屬性和方法。 33 console.log(s) 34 35 var pro = new Programmer("JavaScript"); 36 pro.customExtend(p); 37 console.log(pro) 38
2、使用call和apply進行繼承this
首先,瞭解一下call和apply:經過函數名調用方法,強行將函數中的this指向某個對象;
call寫法: func.call(func的this指向的obj,參數1,參數2...);
apply寫法: func.apply(func的this指向的obj,[參數1,參數2...]);
call與apply的惟一區別:在於接收func函數的參數方式不一樣。call採用直接寫多個參數的方式,而apply採用是一個數組封裝全部參數。
② 使用call和apply
1:定義父類
funtion Parent(){}
2:定義子類
function Son(){}
3:在子類中經過call方法或者apply方法去調用父類。
function Son(){
Parent.call(this,....);
}spa
1 function Person(name,age){ 2 this.name = name; 3 this.age = age; 4 this.say = function(){ 5 alert("我叫:"+this.name+";今年:"+this.age+"歲"); 6 } 7 } 8 function Student(no,stuName,stuAge){ 9 10 this.no = no; 11 Person.call(this,stuName,stuAge); 12 } 13 var stu = new Student(12,"zhangsan",14); 14 stu.say(); 15 16 console.log(stu)
3、使用原型繼承prototype
③ 使用原型繼承
1:定義父類
function Parent(){}
2:定義子類
function Son(){}
3:把在子類對象的原型對象聲明爲父類的實例。
Son.prototype = new Parent();code
1 function Person(name,age){ 2 this.name = name; 3 this.age = age; 4 this.say = function(){ 5 alert("我叫:"+this.name+";今年:"+this.age+"歲"); 6 } 7 } 8 function Student(no){ 9 this.no = no; 10 } 11 12 Student.prototype = new Person("張三",14) 13 14 var stu = new Student(12); 15 16 stu.say(); 17 18 console.log(stu)
但願以上代碼可以幫助讀者解決繼承的問題!對象