JS new.target vs. instanceof



所以我已经阅读了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可能是一个更容易阅读的scosche,但这仅仅是因为它少了一组父()

有人能提供我所缺少的见解吗?谢谢

使用这个Foo实例,您将检查这个实例是否是Foo,但您不能确保它是用新的调用的。我可以做这样的

var foo = new Foo("Test");
var notAFoo = Foo.call(foo, "AnotherWord"); 

而且会很好地工作。使用new.target可以避免此问题。我建议你读这本书https://leanpub.com/understandinges6/read

最新更新