三種方法判斷是否為new調用構造函數


1:在構造函數內部使用嚴格模式,這樣this的指向為undefined,為uneducated添加屬性和方法會直接報錯!

        function Foo() {
            'use strict'
            this.name = 'zhangsan';
            this.age = 18;
        }
        //TypeError: Cannot set property 'name' of undefined
        var a = Foo();

 

2:使用instanceof判斷tthis的指向

        function Foo() {
            if (!(this instanceof Foo)) throw new Error('cuowu!');
            this.name = 'zhangsan';
            this.age = 18;
        }
        //Error: cuowu!
        var a = Foo();

這里如果默認調用this會指向全局對象,而如果使用new調用,this的指向為Foo的實例對象.。

 

3:使用new target方法判斷

 

        function Foo() {
            if (new.target !== Foo) throw new Error('cuowu!');
            this.name = 'zhangsan';
            this.age = 18;
        }
        //Error: cuowu!
        var a = Foo();

 

如果不是new調用,target默認指向的是undefined。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM