javascript考點 —— 面向物件
阿新 • • 發佈:2018-12-05
一、類與例項
1、類的宣告
function Animal(name){
this.name = name
}
class Animal1{
constructor(name){
this.name = name
}
}
2、類的例項化
new Animal('dog')
new Animal1('cat')
二、類與繼承
1、繼承方式
- 藉助建構函式實現繼承
function Parent1(){ this.name = 'parent' } function Child(){ Parent1.call(this) this.type = 'child' } //子類不能繼承父類原型物件上的方法
2、藉助原型鏈實現繼承
function Parent2(){
this.name = 'parent'
}
function Child2(){
this.type = 'Child2'
}
Child2.prototype = new Parent2()
//例項物件對原型屬性的修改,例項之間的相互影響的
3、建構函式、原型組合方式
function Parent3() { this.name = 'parent' this.play = [1,2,3] } function Child3() { Parent3.call(this); this.type = 'child3'; } Child3.prototype = new Parent3() //結合了建構函式繼承和原型繼承的優點,同時避免了它們的缺點。 //但是這裡的父級建構函式Parent3執行了兩次,無法區分它是哪個建構函式直接例項化得來的
4、組合繼承的優化
function Parent4() {
this.name = 'parent'
this.play = [1,2,3]
}
function Child4() {
Parent4.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
//這時父類建構函式Parent4只執行了一次
//但是無法區分例項是父類建構函式例項化的還是子類例項化的
5、組合繼承優化二(這是最完美的寫法)
function Parent5() { this.name = 'parent' this.play = [1,2,3] } function Child5() { Parent5.call(this); this.type = 'child5'; } Child5.prototype = Object.create(Parent5.prototype) Child5.prototype.constructor = Child5 //做到了子類物件和父類物件的隔離