【问题标题】:Restrict a function to only get called with "new" operator [duplicate]将函数限制为仅使用“new”运算符调用[重复]
【发布时间】:2018-06-13 11:55:45
【问题描述】:
var Test = function () {
    console.log("something");
}

我只想通过输入“new”来调用这个函数,即 new Test(); 以这种方式调用时应该抛出错误。测试();

【问题讨论】:

标签: javascript


【解决方案1】:

new.target 属性可让您检测是否使用 new 运算符调用了函数或构造函数。在使用 new 运算符实例化的构造函数和函数中,new.target 返回对构造函数或函数的引用。在正常的函数调用中,new.target 是未定义的。 (无耻抄自MDN)

var Test = function () {
    if (!new.target) throw 'Test() must be called with new';
    console.log("something");
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target

【讨论】:

  • 请在您的答案中添加一些 cmets 来解释您的代码!
猜你喜欢
  • 1970-01-01
  • 2011-06-09
  • 2017-01-14
  • 2011-04-26
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
相关资源
最近更新 更多