Class类

  • 以前创立构造函数

    function Person(name){this.name = name}Person.prototype.say = function(){console.log( `hi, my name is ${this.name}`);}
  • ES6 的类,齐全能够看作构造函数的另一种写法

    class Point {// ...}typeof Point // "function"Point === Point.prototype.constructor // true
    class Point {constructor() {  // ...}toString() {  // ...}toValue() {  // ...}}// 等同于Point.prototype = {constructor() {},toString() {},toValue() {},};
  • constructor 办法

一个类必须有constructor()办法,如果没有显式定义,一个空的constructor()办法会被默认增加

constructor()办法默认返回实例对象(即this),齐全能够指定返回另外一个对象

class Foo {  constructor() {    return Object.create(null);  }}new Foo() instanceof Foo// false
  • 实例办法,静态方法 static

    class Person{ //定义一个person类型constructor(name){ //构造函数  this.name = name  //以后person类型的实例对象}say(){  console.log( `hi, my name is ${this.name}`);}static create (name){ //静态方法外部this不会指向某个实例对象,而是以后的类型  return new Person(name)}}const p = new Person("mcgee")p.say()const jack = Person.create("jack")jack.say()
  • 类的继承 extends

子类必须在constructor办法中调用super办法,否则新建实例时会报错。这是因为子类本人的this对象,必须先通过父类的构造函数实现塑造,失去与父类同样的实例属性和办法,而后再对其进行加工,加上子类本人的实例属性和办法。如果不调用super办法,子类就得不到this对象

class Student extends Person{  constructor(name,number)  {    super(name) //super对象,始终指向父类,调用它就是调用父类的构造函数    this.number = number  }  hello(){    super.say()    console.log(`my school number is ${this.number}`);  }}const ex = new Student("mcgee",123)console.log(ex.name);ex.hello()
  • 类不存在变量晋升
new Foo(); // ReferenceErrorclass Foo {}
  • 父类静态方法也会被子类继承
class A {  static hello() {    console.log('hello world');  }}class B extends A {}B.hello()  // hello world