function person(name){
if(new.target){
new throw('Please call with new operator')
}
this.name = name
}
var a = new person(); // correct wy
person(); // will give error to user
我们是否可以限制用户仅使用new
调用函数。如果他在没有new
运算符的情况下调用,他将获得error
我试过上面的
你能建议更好的方法吗?
答案 0 :(得分:2)
您的代码存在的问题是new.target
仅在使用new
进行调用时才存在。条件应为!new.target
:
function Person(name) {
if (!new.target) throw ('Please call with new operator')
this.name = name
}
var a = new Person('Moses');
console.log(a);
Person();

另一种选择是使用ES6 class。尝试将类作为函数调用将引发错误:
class Person {
constructor(name) {
this.name = name;
}
}
var a = new Person('Moses');
console.log(a);
Person();