3

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 Answers1

4

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

Waldemar Neto
  • 756
  • 5
  • 14
  • 1
    Even better: `foo.constructor("AnotherWord")` – Bergi May 05 '16 at 21:42
  • @Bergi Are you sure your this way will work ? object cant access constructor like this but only the prototype can. I mean if 'foo' is the prototype then only your mentioned code will work – Sumer Dec 28 '19 at 10:09
  • @Sumer Yes, it will work - the `foo` object *inherits* from the prototype so you can access the `.constructor` property on it. – Bergi Dec 28 '19 at 11:23