微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【ECMAScript 5_6_7】14、ES6——模拟面向对象的class

class关键词:

1. 通过class定义类/实现类的继承
2. 在类中通过constructor定义构造方法
3. 通过new来创建类的实例
4. 通过extends来实现类的继承
5. 通过super调用父类的构造方法
6. 重写从父类中继承的一般方法
<!DOCTYPE html>
<html lang="en">
<head>
  <Meta charset="UTF-8">
  <title>12_class</title>
</head>
<body>
</body>
<script type="text/javascript">
  class Person{
    //调用类的构造方法
    constructor(name,age){
      this.name = name
      this.age = age
    }
    //定义一般的方法
    showName(){  // showName()是放在Person原型上的方法,所以新new的Person实例对象都可以继承
      console.log('这是父类方法')
      console.log(this.name,this.age)
    }
  }
  let p1 = new Person('one',20)
  console.log(p1)  // Person {name: "one", age: 20}
  p1.showName()  // 这是父类方法 one 20

  //定义一个子类
  class StrPerson extends Person{
    constructor(name,age,salary){
      super(name,age)  // 调用父类的构造方法
      this.salary = salary
    }
    showName(){  // 这里重写继承父类方法
      console.log('这是子类的方法')
      console.log(this.name,this.age,this.salary)
    }
  }
  let p2 = new StrPerson('dean',21,15000)
  console.log(p2)  // StrPerson {name: "dean", age: 21, salary: 15000}
  p2.showName()  // 这是子类的方法 dean 21 15000

</script>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐