在ES5与ES6中class其实背后的原理是一样的
我们先看Es5是如何定义一个class的
// 首先我们先定义一个动物类 let Animal = function (type) { this.type = type } // 因为有些方法是动物们共有的属性那么我们定义一个原型方法 Animal.prototype.eat = function () { console.log('吃') } // 实例化对象 let dog = Animal('dog') let monkey = Animal('monkey') // 打印 console.log(dog) console.log(monkey) // Animal {type: "dog"} // lesson2.js:15 Animal {type: "monkey"} // 如果我们需要修改原型链上面的方法呢? // 我们可以随便找一个实例 monkey.constructor.prototype.eat = function() { console.log('不吃') }下面我们在ES6中声明一个class
class Animal{ constructor(type) { this.type = type } eat() { console.log('吃') } } // 实例化 let dog = new Animal('dog') let mokey = new Animal('monkey')
评论一下?