ES6学习笔记三

class

关于类 ES6之前使用function定义:

function Child(name){
    this.name = name;
}

ES6引入class 关键字,用于定义类:

class Child {
    constructor(name){
        this.name = name;
    }
}

类的方法实际上都是定义在prototype对象上的,可以使用Object.assgin()在prototype上添加方法;

prototype对象的constructor指向类本身,即:

Child.prototype.constructor === Child; // true

类采用了严格模式,在类内部定义的方法都是不可枚举的,constructor若没有显示定义,会自动加上,类的属性名可以使用表达式;

在constructor内 new.target指向类本身,但是在继承的子类中,指向子类:

class Parent {
    constructor(name){
        this.name = name;
        console.log(new.target === Parent); // false
    }
}
class Child extends Parent{
    constructor(name){
        super(name);
    }
}
let c = new Child("asd");
原文地址:https://www.cnblogs.com/qingxiawu/p/8706876.html