Class

# Class

# 创建

// es5
function Animal(type){
  this.type = type
}
Animal.prototype.eat = function(){
  console.log('i am eating')
}

// es6
class Animal {
  constructor(type){
    this.type = type
  }
  eat(){
    console.log('i am eating')
  }
}

# get 和 set

get 控制获取数据

set 控制设置数据

class Animal {
  constructor(type){
    this.realname = 'name';
    this.type = type
  }
  eat(){
    console.log('i am eating')
  }
  get name (){
    return this.realname
  }
  set name (val){
    this.realname = val
  }
}

# 静态方法

// es5
function Animal(type){
  this.type = type
}
Animal.prototype.eat = function(){
  Animal.work() // 只能使用构造函数调用 不能用 this 调用
  console.log('i am eating')
}
Animal.work = function(){
  console.log('i am working')
}

// es6
class Animal {
  constructor(type){
    this.type = type
  }
  eat(){
    Animal.work() // 只能使用构造函数调用 不能用 this 调用
    console.log('i am eating')
  }
  static work(){
    console.log('i am working')
  }
}

# 继承

# es5继承

function Animal(type){
  this.type = type
}
Animal.prototype.eat = function(){
  Animal.work() // 只能使用构造函数调用 不能用 this 调用
  console.log('i am eating')
}
Animal.work = function(){
  console.log('i am working')
}

function Dog(name){
  Animal.call(this, name) // 继承属性
  this.run = function(){
    console.log('i can run')
  }
}
Dog.prototype = Animal.prototype; // 集成原型链

# es6继承

class Animal {
  constructor(type){
    this.type = type
  }
  eat(){
    Animal.work() // 只能使用构造函数调用 不能用 this 调用
    console.log('i am eating')
  }
  static work(){
    console.log('i am working')
  }
}

class Dog extends Animal {
  constructor(type){
    super(type) // super 继承,放第一行
    this.name = 'dog'
  }
}