你可能不知道的 new.target

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 在外部使用会报错

转载于:https://www.cnblogs.com/qiqingfu/p/10206477.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值