生活随笔
收集整理的這篇文章主要介紹了
面象对象
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
function Animal () { this.name =
'name';}
復制代碼class Animal2 {
constructor() {this.name =
'name'}
}
復制代碼// 實例化
console.log(new Animal(),new Animal2())
復制代碼function Parent1() {this.name =
'parent1'
}Parent1.prototype.say =
function () {console.log(
'say')
}
function Child1() {Parent1.call(this) // apply 改變函數上下文(this)this.type =
'child1'
}console.log(new Child1)
// console.log(new Child1().say()) // say方法如果在構造函數里面可以實現繼承,但如果父類的原型對象上還有方法,子類是拿不到方法。
復制代碼借助原型鏈實現繼承
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共用一原型對象,一個改變另外一個也會改變。
復制代碼組合方式實現繼承
// 寫面向對象繼承的通用方式
// (缺點)父類執行兩次。
function Parent3() {this.name =
'parent3';this.play = [1, 2, 3]
}
function Child3() {Parent3.call(this); // Parent3執行第一次this.type =
'child3'
}Child3.prototype = new Parent3(); // Parent3執行第二次
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。
復制代碼組合方式實現繼承(優化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。
復制代碼組合方式實現繼承(優化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
復制代碼
轉載于:https://juejin.im/post/5bd69a4de51d457a9b6c853c
總結
以上是生活随笔為你收集整理的面象对象的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。