将函数限制为仅使用" new"操作者

时间:2018-06-13 11:55:46

标签: javascript

var Test = function () {
    console.log("something");
}

我只想通过放置" new"来调用此函数。即新的测试(); 以这种方式调用时应该抛出错误。试验();

1 个答案:

答案 0 :(得分:0)

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