new.target属性_你可能不知道的(new.target)

作者:一条鱼
围观群众:302
更新于


使用场景

  • 若是一个组织函数不通过 new 下令天生实例, 就报错提醒

es5中是这样做的:

new.target属性_你可能不知道的(new.target)
    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/archive/2019/01/01/10206477.html


思源资源网:分类流动

1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入

2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入

3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入

链接: http://www.fly63.com/article/detial/1742

new.target属性_你可能不知道的(new.target)

非特殊说明,本文版权归 金科常识网 所有,转载请注明出处.

本文分类: 文化

本文标题: new.target属性_你可能不知道的(new.target)

本文网址: http://sddljzx.com/wenhua/2296.html

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

网站分类
搜索
最新留言
标签列表