JS new.target 与 instanceof

Rhe*_*owe 4 javascript instanceof new-operator

new.target所以我对Node 6.x 中添加的布尔值做了一些阅读。这是MDNnew.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"
Run Code Online (Sandbox Code Playgroud)

但这读起来很像我目前使用下面的代码

var Foo = function (options) {
  if (!(this instanceof Foo)) {
    return new Foo(options);
  }

  // do stuff here
}
Run Code Online (Sandbox Code Playgroud)

new.target我的问题是:超过方法实例有什么好处吗?我并不认为这两者更清楚。new.target可能是 scosche 更容易阅读,但只是因为它少了一组括号()

谁能提供我所缺少的见解?谢谢!

Wal*_*eto 6

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

var foo = new Foo("Test");
var notAFoo = Foo.call(foo, "AnotherWord"); 
Run Code Online (Sandbox Code Playgroud)

并且会工作得很好。使用new.target可以避免这个问题。我建议你阅读这本书https://leanpub.com/understandes6/read