初探 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())复制代码
相关文章
相关标签/搜索