js中的类

ES5 prototype

function Dog(name){
  this.name = name
  this.legs = 4
}
Dog.prototype.say = function(){
  console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'

const d1 = new Dog('tom')
const d2 = new Dog('jimmy')
d1.say()
d2.say()

在prototype中放置可共享的属性(避免内存浪费),在函数中放置各自的私有属性

ES6 class

class Dog {
  kind = '狗'
  constructor(name){
    this.name = name
    this.legs = 4
  }
  say(){
  }
  run(){
  }
}
const d1 = new Dog('jimmy')
d1.say()

js原型链继承的实现

function Animal(legsNumber){
  this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'
function Dog(name){
  Animal.call(this,4) // this.legsNumber = 4
  this.name = name
}
// Dog.prototype.__proto__ = Animal.prototype 不是所有浏览器都存在__proto__属性
var emptyAnimal = function(){}
emptyAnimal.prototype = Animal.prototype
Dog.prototype = new emptyAnimal()
Dog.prototype.say = function(){
  console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'

new的作用:

  1. 创建临时对象
  2. this = 临时对象
  3. 'this.proto' = 构造函数的prototype
  4. 执行构造函数
  5. return this

我们希望执行上面的1,2,3,5,因为4在我们声明Dog时已经使用,所以我们需要构建一个空的函数体的emptyAnimal,然后我们执行Dog.prototype = new emptyAnimal()就能完成继承

es6 class 继承

class Animal {
  constructor(legsNumber){
    this.legsNumber = legsNumber
  }
  run(){}
}
class Dog extends Animal{
  constructor(name){
    super(4)
    this.name = name
  }
  say(){
    console.log(`${this.name} ${this.legsNumber}`)
  }
}

你可能感兴趣的:(js中的类)