关于ecmascript:Class类

11次阅读

共计 1369 个字符,预计需要花费 4 分钟才能阅读完成。

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(); // ReferenceError
class Foo {}
  • 父类静态方法也会被子类继承
class A {static hello() {console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world
正文完
 0