es5和es6中怎么声明一个类

//es5

let Animal = function(type){

   this.type = type

}

Animal.prototype.eat = function (){

   console.log('eat food')

}

let dog = new Animal('dog')

let monkey = new Animal('monkey')

monkey.constructor.prototype.eat = function (){

   console.log('eating')

}

dog.eat()

monkey.eat()

//es6

class Animal{

   constructor(type){

      this.type = type

   }

   eat(){

       console.log('eating')

   }

}

let dog = new Animal('dog')

let monkey = new Animal('monkey')

console.log(dog)

console.log(monkey)

dog.eat()

monkey.eat()

语法糖:语法不同,效果一样

上一篇:ES5 Array 映射过滤汇总 源码实现 ( map / filter / reduce ) 面试必备


下一篇:ES5和ES6中的一些综合应用(持续更新)