简单了解ES6中的class类
ES6中的class类
-
通过class定义类/实现类的继承
-
在类中通过constructor定义构造方法
-
通过new来创建类的实例
-
通过extends来实现类的继承
-
通过super调用父类的构造方法
-
重写从父类中继承的一般方法
-
通过static来创建类的 静态方法/静态属性
举例:(注意定义class类里的方法必须使用简化对象的写法 。就是省略function)
//通过class定义类 //生成一个Person类 class Person{ //在类中通过constructor定义构造方法 constructor(name,age) { this.name=name; this.age=age; } //普通方法 //function getInfo() //必须使用简化对象的写法 否则报错 getInfo() { console.log(this.name,this.age); } } //通过extends来实现类的继承 class DoctorPerson extends Person{ //生成一个静态属性 static say="hello"; constructor(name,age,salary) { //通过super调用父类的构造方法 super(name,age); this.salary=salary; } //重写从父类中继承的一般方法 getInfo() { console.log(this.name,this.age,this.salary); } //生成一个静态方法 static getColor(color) { console.log(color); } } //通过new来创建类的实例 let person=new Person("Tom",23); person.getInfo(); //Tom 23 //实例化一个DoctorPerson类对象 let doctor=new DoctorPerson("Jack",33,8000); doctor.getInfo(); //Jack 33 8000 //调用静态属性 console.log(DoctorPerson.say); //hello //重新赋值 DoctorPerson.say="hi"; console.log(DoctorPerson.say); //hi //调用静态方法 DoctorPerson.getColor("pink"); //pink
类的方法名 可以采用表达式
let funName="fun"; class Test{ [funName](){ console.log("functionName"); } } let test=new Test(); test.fun(); //functionName
new.target 属性
该属性一般用在构造函数之中。如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。
function Person(name) { if (new.target !== undefined) { this.name = name; } else { throw new Error('必须使用 new 命令生成实例'); } } // 另一种写法 function Person(name) { if (new.target === Person) { this.name = name; } else { throw new Error('必须使用 new 命令生成实例'); } } var person = new Person('张三'); // 正确 var notAPerson = Person.call(person, '张三'); // 报错
上面代码确保构造函数只能通过new命令调用。
Class 内部调用new.target,返回当前 Class。
class Rectangle { constructor(length, width) { console.log(new.target === Rectangle); this.length = length; this.width = width; } } var obj = new Rectangle(3, 4); // 输出 true
需要注意的是,子类继承父类时,new.target会返回子类。
class Rectangle { constructor(length, width) { console.log(new.target === Rectangle); // ... } } class Square extends Rectangle { constructor(length, width) { super(length, width); } } var obj = new Square(3); // 输出 false
注意:类不存在变量提升。和继承有关,必须保证子类在父类之后定义。