js class类


class 定义类

class Person{
	// 这个方法会被定义在类的原型对象上
    identify(){
        console.log(Person.name , PersonName.name);
     }
    
    // new.target 指向当前构造函数
    // 将这个类变为抽象基类,即这个类不能实例化对象
    if(new.target === Person){
        throw new Error("Person cannot be directly instantiated")
    }
    
    // 在调用构造函数之前原型对象就已经存在了
    // 在实例对象的原型上必须要有这个foo方法,否则会报错,这里决定了Person的派生类必须要有foo这个方法
    if(!this.foo){
        throw new Erro("Inheriting class must define foo()")
    }
    
}

在继承原生类型时,会拥有原生类型所有的方法,这些方法中有的会返回内置类型的元素(比如数组的filter会返回一个新的数组对象),但是在使用这些派生类创建的实例对象使用这些方法时,返回的元素将会是该派生类的实例,解决方法:

// Symbol.species 这个访问器决定在创建返回实例时使用的类
class SuperArray extends Array{
    static get [Symbol.species](){
		return Array
	}
}

类中this的指向,类中的方法默认开启了严格模式

class Person{
      constructor(name,age){
        this.name = name
        this.age = age
      }
      study(){
        console.log(this);
      }
    }
    const student = new Person('张三',19)
    student.study() // student
    const x = student.study
    x() // undefined
js