以下代碼可以直接放到控制臺(tái)看運(yùn)行結(jié)果
1袍榆、借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承沦泌,缺點(diǎn)是不能繼承Parent1的原型對(duì)象
// 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承
function Parent1() {
this.name = 'parent1';
this.play = [1, 2, 3];
}
function Child1() {
Parent1.call(this); //apply
this.type = 'Child1';
}
console.log(new Parent1(), new Child1());
var s1 = new Child1();
var s2 = new Child1();
console.log(s1, s2);//未繼承原型對(duì)象
console.log(s1.play, s2.play);
s1.play.push(4);
console.log(s1.play, s2.play);
Parent1.prototype.age = 20;
console.log(s1.age, s2.age);
2、借助原型鏈實(shí)現(xiàn)繼承费奸,缺點(diǎn)是共享屬性和方法
//借助原型鏈實(shí)現(xiàn)繼承
function Parent2() {
this.name = 'parent2';
this.play = [1, 2, 3];
}
function Child2() {
this.type = 'Child2';
}
Child2.prototype = new Parent2();
var s3 = new Child2();
var s4 = new Child2();
console.log(s3, s4);
console.log(s3.play, s4.play);
s3.play.push(4);
console.log(s3.play, s4.play);//s3和s4的屬性和方法共享
3弥激、組合方式實(shí)現(xiàn)繼承(原型鏈繼承+綁定this),缺點(diǎn)是Parent3執(zhí)行兩次
// 組合方式
function Parent3() {
this.name = 'parent3';
this.play = [1, 2, 3];
}
function Child3() {
Parent3.call(this);
this.type = 'Child3';
}
Child3.prototype = new Parent3();
var s5 = new Child3();
var s6 = new Child3();
console.log(s5, s6);//繼承了parent3的原型對(duì)象
console.log(s5.play, s6.play);
s5.play.push(4);
console.log(s5.play, s6.play);//s5和s6數(shù)據(jù)對(duì)象不同
4愿阐、組合方式實(shí)現(xiàn)繼承優(yōu)化一微服,缺點(diǎn)是無(wú)法區(qū)分實(shí)例是由父類(lèi)創(chuàng)造還是子類(lèi)創(chuàng)造
//組合方式優(yōu)化一
function Parent4() {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4() {
Parent4.call(this);
this.type = 'Child4';
}
Child4.prototype = Parent4.prototype; //不用實(shí)例化一個(gè)Parent4對(duì)象
var s7 = new Child4();
var s8 = new Child4();
console.log(s7.play, s8.play);
s7.play.push(4);
console.log(s7.play, s8.play);
console.log(s7.constructor); //缺點(diǎn)是Child4和Parent4的原型對(duì)象相同,構(gòu)造函數(shù)相同
// console.log(Child4.prototype.constructor);
// console.log(s5.__proto__.constructor);
// console.log(s5.__proto__ === Child4.prototype);
5缨历、組合方式實(shí)現(xiàn)繼承優(yōu)化二(最優(yōu)寫(xiě)法)
// 組合繼承的優(yōu)化2(完美寫(xiě)法)
function Parent5() {
this.name = 'parent5';
this.play = [1, 2, 3];
}
function Child5() {
Parent5.call(this);
this.type = 'Child5';
}
Child5.prototype = Object.create(Parent5.prototype); //Child5原型對(duì)象是Obejct.create方法的參數(shù)
//Object.create方法會(huì)丟失原構(gòu)造函數(shù)屬性
//它的原型鏈也是原構(gòu)造函數(shù)(對(duì)象)本身以蕴,因此還需要指定constructor
Child5.prototype.constructor = Child5;
var s9 = new Child5();
var s10 = new Child5();
s9.play.push(4);
console.log(s9.play, s10.play);
console.log(s9.constructor);
console.log(s9.__proto__ === Child5.prototype);
Parent5.prototype.age = 20;
console.log(s9.age, s10.age);