new 是构造函数生成实例的命令, ES6为 new 命令引入了 new.target属性。这个属性用于确定构造函数是怎么调用的。

在构造函数中, 如果一个构造函数不是通过 new操作符调用的, new.target会返回 undefined。

使用场景

  • 如果一个构造函数不通过 new 命令生成实例, 就报错提醒

es5中是这样做的:

    function Shape(options) {
        if (this instanceof Shape) {
            this.options = options
        } else {
            // 要么手动给它创建一个实例并返回
            // return new Shape(options)
            
            // 要么提醒
            throw new Error('Shape 构造函数必须使用 new 操作符')
        }
    }

es6中可以这样做:

    function Shape(options) {
        // if (new.target !== 'undefined') {}  必须要在 constructor中使用 new.target, 在这里判断会报错
        
        constructor(options) {
            if (new.target !== 'undefined') {
                this.options = options
            } else {
                throw new Error('必须使用 new 操作符')
            }
        }
    }

以上代码通过 new.target 属性判断返回的是不是undefined即可知道这个构造函数是不是通过 new 操作符调用

  • 一个构造函数只能用于子类继承, 自身不能 new

new.target这个属性,当子类继承父类会返回子类的构造函数名称

    class Parent {
        constructor() {
            console.log(new.target)
        }
    }
    
    class Child extends Parent {
        constructor() {
            super()
        }
    }
    
    // Child

以上代码 Child子类继承父类, 那么父类构造函数中的 new.target 是子类构造函数的名称。

规定构造函数只能用于继承
    class Zoo {
        constructor() {
            if (new.target === Zoo) throw new Error('Zoo构造函数只能用于子类继承')
        }
    }
    
    const zoo = new Zoo()   // 报错
    
    class Dog extends Zoo {
       constructor() {
           super()
       } 
    }
    
    const dog = new Dog()  // 不报错

tip : new.target 在外部使用会报错

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程