javascript - 如何限制用户只能使用新运算符(operator)调用功能?

标签 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 运算符,他将得到错误 我像上面那样试过

你能推荐更好的方法吗?

最佳答案

您的代码的问题是 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/

相关文章:

javascript - 如何在javascript中隐藏多个元素?

javascript - 将get查询中的参数传递给vue js?

javascript - 如何在 jQuery-validate 中指定验证字段

javascript - 创建数组的函数

javascript - 如何根据时间更改边框颜色

javascript - 未捕获( promise )类型错误 : Something went wrong while trying to open the window

javascript - file.slim.js 中的 slim 是什么

javascript - HTML5 Canvas : Thousand of moving Images = Huge FPS loss

javascript - 从 api 获取数据后在 React 中显示嵌套对象?

javascript - 从 FileReader 设置 backgroundImage 样式