初探 JavaScript 面向對象

類的聲明

1. 構造函數bash

function Animal() {
  this.name = 'name'
}

// 實例化
new Animal()複製代碼

2. ES6 class函數

class Animal {
  constructor() {
    this.name = 'name'
  }
}

// 實例化
new Animal()複製代碼

類的繼承

1. 藉助構造函數實現繼承ui

原理:改變子類運行時的 this 指向,可是父類原型鏈上的屬性並無被繼承,是不徹底的繼承this

function Parent() {
  this.name = 'Parent'
}

Parent.prototype.say = function(){
  console.log('hello')
}

function Child() {
  Parent.call(this)
  this.type = 'Child'
}

console.log(new Parent())
console.log(new Child())複製代碼

2. 藉助原型鏈實現繼承spa

原理:原型鏈,可是在一個子類實例中改變了父類中的屬性,其餘實例中的該屬性也會改變子,也是不徹底的繼承prototype

function Parent() {
  this.name = 'Parent'
  this.arr = [1, 2, 3]
}

Parent.prototype.say = function(){
  console.log('hello')
}

function Child() {
  this.type = 'Child'
}

Child.prototype = new Parent()

let s1 = new Child()
let s2 = new Child()
s1.arr.push(4)
console.log(s1.arr, s2.arr)

console.log(new Parent())
console.log(new Child())
console.log(new Child().say())複製代碼

3. 構造函數 + 原型鏈3d

最佳實踐code

// 父類
function Parent() {
  this.name = 'Parent'
  this.arr = [1, 2, 3]
}

Parent.prototype.say = function(){
  console.log('hello')
}

// 子類
function Child() {
  Parent.call(this)
  this.type = 'Child'
}

// 避免父級的構造函數執行兩次,共用一個 constructor
// 可是沒法區分實例屬於哪一個構造函數
// Child.prototype = Parent.prototype

// 改進:建立一箇中間對象,再修改子類的 constructor
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

// 實例化
let s1 = new Child()
let s2 = new Child()
let s3 = new Parent()
s1.arr.push(4)
console.log(s1.arr, s2.arr) //  [1, 2, 3, 4] [1, 2, 3]
console.log(s2.constructor) // Child
console.log(s3.constructor) // Parent

console.log(new Parent())
console.log(new Child())
console.log(new Child().say())複製代碼
相關文章
相關標籤/搜索