JS new.target 与 instanceof
JS new.target vs. instanceof
所以我阅读了一些关于节点 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
可能是 scosche 更容易阅读,但这只是因为它少了一组括号 ()
。
任何人都可以提供我所缺少的见解吗?谢谢!
使用 this instanceof Foo 你将检查这个实例是否是 Foo,但你不能确保它是用 new[=19= 调用的].
我可以做这样的事情
var foo = new Foo("Test");
var notAFoo = Foo.call(foo, "AnotherWord");
并且会正常工作。使用 new.target 可以避免这个问题。
建议你看看这本书https://leanpub.com/understandinges6/read
所以我阅读了一些关于节点 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
可能是 scosche 更容易阅读,但这只是因为它少了一组括号 ()
。
任何人都可以提供我所缺少的见解吗?谢谢!
使用 this instanceof Foo 你将检查这个实例是否是 Foo,但你不能确保它是用 new[=19= 调用的]. 我可以做这样的事情
var foo = new Foo("Test");
var notAFoo = Foo.call(foo, "AnotherWord");
并且会正常工作。使用 new.target 可以避免这个问题。 建议你看看这本书https://leanpub.com/understandinges6/read