如何用新的运算符来限制用户调用函数?

时间:2018-05-05 09:15:30

标签: javascript

 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 我试过上面的

你能建议更好的方法吗?

1 个答案:

答案 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();