问题
So I have done some reading on the new.target
boolean added in Node 6.x. Here is a simple example of new.target
provided on MDN
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"
But this reads a lot like what I am presently using the below code for
var Foo = function (options) {
if (!(this instanceof Foo)) {
return new Foo(options);
}
// do stuff here
}
My question is this: Is there any benifit to new.target
over the instance of method? I don't particularly see either as more clear. new.target
may be a scosche easier to read but only because it has one less set of parens ()
.
Can anyone provide an insight I am missing? Thanks!
回答1:
Using this instanceof Foo you will check if this instance is a Foo, but you can't ensure that was called with a new. I can just do a thing like this
var foo = new Foo("Test");
var notAFoo = Foo.call(foo, "AnotherWord");
And will work fine. Using new.target you can avoid this issues. I suggest you to read this book https://leanpub.com/understandinges6/read
来源:https://stackoverflow.com/questions/37060559/js-new-target-vs-instanceof