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
运算符,他将得到错误
我像上面那样试过
你能推荐更好的方法吗?
最佳答案
您的代码的问题是 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();
关于javascript - 如何限制用户只能使用新运算符(operator)调用功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187748/