欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ES6中的class

程序员文章站 2023-12-21 13:03:16
...

基本用法

ES6中的class实际上是对象原型写法的语法糖 它的主要意义是使其更接近面对对象的语法

function Cat (name, age) {
  this.name = name
  this.age = age
}
Cat.prototype.toString = function () {
 return 'name: ' + this.name + ', age:' + this.age
}

let kitty = new Cat('kitty', 1)
复制代码

将上述代码用class改写

class Cat {
  constructor(name, age) {
    this.name = name
    this.cat = cat
  }
  toString() {
    return  'name: ' + this.name + ', age:' + this.age
  }
}
复制代码

class中的继承

class通过关键字extends实现继承

class Felinae extends Cat {
  constructor (name, age, color) {
    super(name, age)      //super关键字调用了父类的构造函数, 子类必须调用super()方法,否则会报错,因为子类没有自己的this对象,而是继承父类的this对象
    this.color = color
  }
}
复制代码

转载于:https://juejin.im/post/5a31012c51882554bd510d39

上一篇:

下一篇: