es6 class

 

 类的语法结构

class name [extends] {
  // class body
}
注意:构造方法和实例方法之间没有任何标点符号,特别是没有,
constructor构造函数 (如果有属性值,就需要写constructor构造函数,如果没有属性值,
constructor可以省略,JavaScript 引擎会自动为它添加一个空的constructor方法。)
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法
一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。

static functionName(){}
静态方法:
静态方法,也叫类方法 ,当前类.静态方法。实例对象不能打点调用
静态方法中的this指代当前类。而不是实例对象
父类静态方法可以被子类继承
 
class Person {
  // static prop=10
  // 构造函数
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  static classMethod() {
    console.log(this); //静态方法中的this是当前类
    console.log('我是静态方法,也叫类方法 ,当前类.静态方法。实例对象不能打点调用');
    this.classMethod1()
  }
  static classMethod1() {
    console.log('我是静态方法2');
  }

  sayName() {
    console.log(this); //this是new 出来的实例对象
    console.log(this.name);
  }

}

const p1 = new Person('zs', 12)

类的继承

如果子类没有自己要扩展的属性 子类的constructor构造函数完全不用写, 由于继承,默认就有name age的属性,只不过属性值都是undefined,实例方法也直接继承过来用。子类默认继承父类所有的实例方法。子类还扩展自己的实例方法
class parent {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  sayName() {
    console.log(this.name);
  }
}

class Son extends parent {
  // 如果子类没有自己要扩展的属性 子类的constructor构造函数完全不用写,
  // 由于继承,默认就有name age的属性,只不过属性值都是undefined,实例方法也直接继承过来用
  // 子类默认继承父类所有的实例方法。子类还扩展自己的实例方法
  sayAge() {
    console.log(this.age);
  }
}
const son1 = new Son('zs', 10) //默认值赋值
console.log(son1); //Son { name: 'zs', age: 10 }
son1.sayName() //'zs 
son1.sayAge()
View Code

子类扩展自己的实例属性时候,就必须显示调用子类自己的constructor构造方法

class Parent {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  static staticMethod() {
    console.log(this); //父类或者子类谁调用staticMethod方法,(Son1.staticMethod()|Parent.staticMethod())this就指代哪个类
    console.log('父类的静态方法可以被子类继承');
  }
  sayName() {
    console.log(this.name);
  }
}

class Son1 extends Parent {
  constructor(name, age, gender) {
    super(name, age)
    this.gender = gender
  }
  sayAge() {
    console.log(this.age);
  }
  sayGender() {
    console.log(this.gender);
  }
}
const son1 = new Son1('zs', 12, 'male')
son1.sayAge()
son1.sayName()
son1.sayGender()
Son1.staticMethod() //[Function: Son1]
Parent.staticMethod() //[Function: Parent]
原文地址:https://www.cnblogs.com/xiaoliziaaa/p/13382520.html