JS new.target vs. instanceof

两盒软妹~` 提交于 2019-12-24 05:08:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!