首页 > 解决方案 > 如何限制用户仅使用新运算符调用函数?

问题描述

 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.if调用函数newerror

你能建议更好的方法吗?

标签: javascript

解决方案


您的代码的问题是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 Person {
  constructor(name) {
    this.name = name;
  }
}

var a = new Person('Moses');

console.log(a);

Person();


推荐阅读