【发布时间】:2016-05-05 21:27:43
【问题描述】:
所以我已经阅读了 Node 6.x 中添加的 new.target 布尔值。这是MDN上提供的new.target的简单示例
function Foo() {
if (!new.target) throw "Foo() must be called with new";
console.log("Foo instantiated with new");
}
Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instantiated with new"
但这读起来很像我目前使用下面的代码
var Foo = function (options) {
if (!(this instanceof Foo)) {
return new Foo(options);
}
// do stuff here
}
我的问题是:new.target 对方法的实例有什么好处吗?我并不特别认为两者都更清楚。 new.target 可能更容易阅读,但这只是因为它少了一组括号 ()。
谁能提供我所缺少的见解?谢谢!
【问题讨论】:
-
你可以在任何实例上调用构造函数,但你可以在没有
new的情况下调用它。 -
new.target不是布尔值!更多解释见here。 -
感谢您的澄清,Bergi
标签: javascript new-operator instanceof