类的声明

  1. class Person{
  2. constructor(name){
  3. this.name = name
  4. }
  5. sayName(){
  6. console.log(this.name)
  7. }
  8. }

通过类的声明语法定义构造函数的行为和之前创建的构造函数的过程类似,只是这里直接在class中通过特殊的constructor方法来定义构造函数。
自身属性是实例中的属性,不会出现在原型链中,且只能在类的构造器或则方法中创建。

为何使用class语法

  • 函数声明可以被提升,而class声明与let声明类似,不能被提升
  • 类声明中所有的代码将自动运行在严格模式下,且无法强行让代码脱离严格模式
  • 类中所有的方法都是不可枚举的
  • 出了new以为的方式调用class会导致程序抛出错误

    继承

    ES6之前的继承

    1. function Rec( length,width){
    2. this.length = length
    3. this.width = width
    4. }
    5. Rec.prototype.getArea = function(){
    6. return this.length*this.width
    7. }
    8. function Square(l,w){
    9. Rec.call(this,l,w)
    10. }
    11. Square.prototype = Object.create(Rec.prototype,{
    12. constructor:Square
    13. })

    ES6之后的继承

    类的出现让我们可以更轻松的实现继承的功能,使用熟悉的extends关键字可以指定类继承的函数。原型可以自动调整,通过调用super()方法即可访问基类的构造函数

    1. class Rec{
    2. constructor(l,w){
    3. this.l=l;
    4. this.w=w
    5. }
    6. getArea(){
    7. return this.l*this.w
    8. }
    9. }
    10. class Squ extends Rec{
    11. constructor(l){
    12. super(l,l)//相当于Rec.call(this,l,l)
    13. }
    14. }
    15. let sq = new Squ(2);
    16. console.log(sq.getArea())