你知道幾種繼承方式?(結尾有彩蛋)
(轉載請註明出處)(๑•ᴗ•๑) 複製程式碼
首先準備一個建構函式(後幾個皆以此為例)
function Person() { this.name = 'person', this.age = 18 } Person.prototype.eat = function () {} 複製程式碼
1原型繼承
function Student() {} Student.prototype = new Person var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ __proto__: Student.prototype { name: 'person', age: 18, __proto__: Person.prototype { eat: function () {}, __proto__: Object.prototype } } } 複製程式碼
優點: 使用簡單,好理解
缺點: 原型鏈多了一層,並且這一層沒什麼用
2借用建構函式繼承
function Student() { Person.call(this) } var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ name: 'person', age: 18, __proto__: Student.prototype { constructor: Student, __proto__: Object.prototype } } 複製程式碼
優點: 直接把屬性變成自己的了
缺點: 沒有父類原型上的東西
3組合繼承
function Student() { Person.call(this) } Student.prototype = new Person } var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ name: 'person', age: 18, __proto__: new Person { name: 'person', age: 18, __proto__: Person.prototype { eat: function () {}, constructor: Person, __proto__: Object.prototype } } } 複製程式碼
優點: 屬性繼承來變成自己的,原型也繼承過來了
缺點: 第一層原型沒用,繼承的原型多走一步
4拷貝繼承
function Student() { var p = new Person for (var key in p) { Student.prototype[key] = p[key] } } var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ __proto__: Student.prototype { name: 'person', age: 18, eat: function () {}, constructor: Student, __proto__: Object.prototype } } 複製程式碼
優點: 屬性和方法都繼承來放在我自己的原型上了
缺點: for in 迴圈,相當消耗效能的一個東西
5寄生繼承
function Student() { this.gender = '男' var p = new Person return p } Student.prototype.fn = function () {} var s = new Student 複製程式碼
這裡很明顯,此時直接得到的是 Person 的例項, this.gender
和 fn()
不會存在在s中
優點: 完美的繼承了屬性和方法
缺點: 根本沒有自己的東西了
6寄生式組合繼承1
function Student() { Person.call(this) } Student.prototype.fn = function () {} Student.prototype = Person.prototype var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ name: 'person', age: 18, __proto__: Person.prototype { eat: function () {}, constructor: Person, __proto__: Object.prototype } } 複製程式碼
優點:原型的東西不需要多走一步
缺點: 沒有自己的原型
7寄生式組合繼承2
function Student() { Person.call(this) } (function () { function Abc() {} Abc.prototype = Person.prototype Student.prototype = new Abc })() var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ name: 'person', age: 18, __proto__: new Abc { __proto__: Person.prototype { eat: function () {} } } } 複製程式碼
優點: 屬性繼承來是自己的,方法也繼承來了,組合式繼承的中間那個環節多餘的屬性沒有了
缺點: 就是多了一個 空環,導致我訪問繼承的方法的時候要多走一步
8混搭式繼承
function Student() { Person.call(this) } (function () { var obj = Person.prototype for (var key in obj) { Student.prototype[key] = obj[key] } })() var s = new Student 複製程式碼
此時在控制檯中檢視S裡是這樣的
{ name: 'person', age: 18, __proto__: Student.prototype { constructor: Student, eat: function () {}, __proto__: Object.prototype } } 複製程式碼
優點: 屬性原型都有了,沒有多餘的空環, constructor
直接指向自己
缺點: for in
迴圈。然後就沒有缺點~~~(因為是自創的hhh)

復聯四你看了嗎?被劇透了嗎-。-好氣喲 複製程式碼