JS new.target与instanceof

时间:2016-05-05 21:27:43

标签: javascript new-operator 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可能更容易阅读,但仅仅是因为它只有少量的parens ()

任何人都可以提供我缺少的见解吗?谢谢!

1 个答案:

答案 0 :(得分:1)

使用此实例Foo ,您将检查此实例是否为Foo,但您无法确保使用 new 调用该实例。 我可以做这样的事情

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

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