如何确保构造函数只能被new调用?

本文介绍了三种在JavaScript中防止构造函数被普通函数调用的方法:1)instanceof判断;2)new.target属性检查;3)ES6类强制使用new。同时提到了每种方法的局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何确保你的构造函数只能被new调用,而不能被普通函数调用?

js中的函数一般有两种形式 new Fun()、fun(); 但是js内部并没有作区分;

  • 所以人为规定构造函数名首字母要大写作为区分;
  • 可以利用instanceof检测某个对象是不是另外一个对象的实例 new Person() instanceof Person --> true
  • 使用new调用函数和普通调用函数的最大区别是在于函数内部的this指向不同;new调用后this指向实例、普通调用则会指向window
        function Person(){
            console.log(this)
        }
	    console.log( new Person() instanceof Person) //true
        Person() //window
        const p = new Person() //Person{}  

第一种方法:instanceof 判断

        function Person(){
            if(!(this instanceof Person)){
                throw new TypeError('普通函数调用')
            }else{
                console.log('new调用')  
            }
        }
        Person() // Uncaught TypeError: 普通函数调用
        new Person() // new调用

		//此方法有点瑕疵,可以通过call、apply改变this指向骗过以上if判断
		Person.call(new Person())

第二种方法:new.target ES6中引入的属性,如果构造函数不是通过 new 命令或 Reflect.construct() 调用的,new.target 会返回 undefined

        function Person(){
            if(!(new.target)){
                throw new TypeError('普通函数调用')
            }else{
                console.log('new调用')  
            }
        }
        Person() // Uncaught TypeError: 普通函数调用
        new Person() // new调用

第三种方法:class、类的构造器必须使用new调用

        class Person{
            constructor(name){
                this.name = name
            }
        }
        //Person()//test.html:15 Uncaught TypeError: Class constructor Person cannot be invoked without 'new'
        const person = new Person('zhangsan')
        console.log(person.name)//zhangsan
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值