
ES6中的class
新的Class类写法【2020用这个】
class Cat {// 用class关键字写个猫咪类constructor (type) {// 这个就是构造函数this.type = type// this 就是实例化后的对象}eat () {// 实例方法现在写在构造函数后console.log('eat Cat food')}}// 新建猫咪的实例对象let luna = new Cat('ChinaCat')let mike = new Cat('BritchCat')// 实例对象使用eat方法luna.eat()mike.eat()
ES5以前仿制class
过时的类写法【淘汰了】【了解一下吧】
// 老版本中类最最古老的写法let Animal = function (type) {this.type = typethis.eat = function () {console.log('eating')}}// 创建对象实例let dog = new Animal('dog')let monkey = new Animal('monkey')// 打印出对象console.log(dog)console.log(monkey)
原理都在原型链上
写在原型链prototype上,可以节约内存,这个才是正规的写法,不然对象会自持有-太占内存空间了
// 写一个Dog类let Dog = function (type) {this.type = type}// eat 方法写在 prototype[原型链] 上Dog.prototype.eat = function () { console.log('eat Dog food') }// 创建实例对象let luce = new Dog('goldenHair')let rose = new Dog('labrador')// 使用实例对象的eat方法luce.eat()rose.eat()
