生活随笔
收集整理的這篇文章主要介紹了
面象对象
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
function Animal () { this.name =
'name';}
復(fù)制代碼class Animal2 {
constructor() {this.name =
'name'}
}
復(fù)制代碼// 實(shí)例化
console.log(new Animal(),new Animal2())
復(fù)制代碼- 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承
function Parent1() {this.name =
'parent1'
}Parent1.prototype.say =
function () {console.log(
'say')
}
function Child1() {Parent1.call(this) // apply 改變函數(shù)上下文(this)this.type =
'child1'
}console.log(new Child1)
// console.log(new Child1().say()) // say方法如果在構(gòu)造函數(shù)里面可以實(shí)現(xiàn)繼承,但如果父類的原型對(duì)象上還有方法,子類是拿不到方法。
復(fù)制代碼借助原型鏈實(shí)現(xiàn)繼承
function Parent2() {this.name =
'Parent2';this.play = [1, 2, 3, 4]
}
function Child2() {this.type =
'child2';
}Child2.prototype = new Parent2()
console.log(new Child2())
console.log(new Child2().__proto__)
var s1 = new Child2()
var s2 = new Child2()s1.play.push(5)
console.log(s1.play, s2.play) // s1,s2共用一原型對(duì)象,一個(gè)改變另外一個(gè)也會(huì)改變。
復(fù)制代碼組合方式實(shí)現(xiàn)繼承
// 寫面向?qū)ο罄^承的通用方式
// (缺點(diǎn))父類執(zhí)行兩次。
function Parent3() {this.name =
'parent3';this.play = [1, 2, 3]
}
function Child3() {Parent3.call(this); // Parent3執(zhí)行第一次this.type =
'child3'
}Child3.prototype = new Parent3(); // Parent3執(zhí)行第二次
var s3 = new Child3()
var s4 = new Child3()
s4.play.push(4)
console.log(s3.play, s4.play)
console.log(s3.constructor)
console.log(s4.constructor) // s3s4的constructor指向是父類Parent3。
復(fù)制代碼組合方式實(shí)現(xiàn)繼承(優(yōu)化1)
function Parent4() {this.name =
'parent4';this.play = [1, 2, 3, 4];
}
function Child4() {Parent4.call(this);this.type =
'child4';
}Child4.prototype = Parent4.prototype; // 引用類型
var s5 = new Child4();
var s6 = new Child4();
s5.play.push(5);
console.log(s5, s6);
console.log(s5 instanceof Child4, s5 instanceof Parent4) //
true,
true
console.log(s5.constructor)
console.log(s6.constructor) // s5s6的constructor指向都是父類Parent4。
復(fù)制代碼組合方式實(shí)現(xiàn)繼承(優(yōu)化2)
function Parent5() {this.name =
'parent5';this.play = [1, 2, 3, 4];
}
function Child5() {Parent5.call(this);this.type =
'child5';
}Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5;
var s7 = new Child5();
console.log(s7 instanceof Child5, s7 instanceof Parent5);
console.log(s7.constructor) // s7的constructor指向Child5
復(fù)制代碼
轉(zhuǎn)載于:https://juejin.im/post/5bd69a4de51d457a9b6c853c
總結(jié)
以上是生活随笔為你收集整理的面象对象的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。