一、類的聲明
//構(gòu)造函數(shù)
function Parent() {
? ? this.firstName = 'Hou';
}
Parent.prototype.say(){
? ? console.log('hello');
}
//ES6
class Parent2(){
? ? consutractor () {
? ? ? ? this.name = 'Zhang';
? ? }
}
二、類的實(shí)例化
var parent= new Parent ();
三、類的繼承
1. 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承
????原理:改變函數(shù)運(yùn)行時(shí)的上下文,即this的指向
function Child1() {
? ? Parent.call(this);
? ? this.lastName = 'Peng';
}
? ? 缺點(diǎn):父類原型對(duì)象上的方法無(wú)法被繼承
console.log(new Child1().say());? ? //出錯(cuò),找不到此方法
2. 借助原型鏈實(shí)現(xiàn)繼承
? ? 原理:改變子類的prototype(即其實(shí)例的__proto__)屬性指向其父類的實(shí)例
function Child2() {
? ? this.lastName = 'Peng';
}
Child2.prototype = new Parent();
? ??原型鏈原理:實(shí)例的__proto__屬性指向其構(gòu)造函數(shù)的prototype屬性
new Child2().__proto__ === Child2.prototype? ? //true
????缺點(diǎn):原型鏈中的原型對(duì)象是共用的,子類實(shí)例的原型對(duì)象是同一個(gè)引用,當(dāng)一個(gè)實(shí)例的屬性改變時(shí),其他實(shí)例也跟著改變
var c21 = new Child2();
var c22 = new Child2();
c21.__proto__ === c22.__proto__? ? //true
3. 組合方式實(shí)現(xiàn)繼承
? ? 原理:結(jié)合構(gòu)造函數(shù)和原型鏈方法的優(yōu)點(diǎn),彌補(bǔ)了此兩種方法的不足? ??
function Child3() {
? ? Parent.call(this);
? ? this.lastName = 'Peng';
}
Child3.prototype = new Parent();
? ? 缺點(diǎn):父類構(gòu)造函數(shù)執(zhí)行了兩次
4. 組合方式實(shí)現(xiàn)繼承的優(yōu)化1
? ? 原理:子類的原型對(duì)象引用父類的原型對(duì)象
function Child4() {
? ? Parent.call(this);
? ? this.lastName = 'Peng';
}
Child4.prototype= Parent.prototype;
? ? 缺點(diǎn):無(wú)法區(qū)分實(shí)例是子類還是父類的實(shí)例,實(shí)例的constructor屬性為父類構(gòu)造函數(shù)(方法2,3也有同樣的缺陷)
var c4 = new Child4();
console.log(c4 instanceof Child4);? ? //true
console.log(c4 instanceof Parent);? ? //true
console.log(c4.constructor);? ? //Parent;
5. 組合方式實(shí)現(xiàn)繼承的優(yōu)化2,完美寫(xiě)法
? ? 原理:利用Object.create()函數(shù)創(chuàng)建的對(duì)象
function Child5() {
? ? Parent.call(this);
? ? this.lastName = 'Peng';
}
Child5.prototype = Object.create(Parent.prototype);
Child5.prototype.constructor = Child5;