【问题标题】:JS new.target vs. instanceofJS new.target 与 instanceof
【发布时间】:2016-05-05 21:27:43
【问题描述】:

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

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

【问题讨论】:

  • 你可以在任何实例上调用构造函数,但你可以在没有new的情况下调用它。
  • new.target 不是布尔值!更多解释见here
  • 感谢您的澄清,Bergi

标签: javascript new-operator instanceof


【解决方案1】:

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

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

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

【讨论】:

  • 更好:foo.constructor("AnotherWord")
  • @Bergi 你确定你的这种方法行得通吗?对象不能像这样访问构造函数,但只有原型可以。我的意思是如果 'foo' 是原型,那么只有你提到的代码才能工作
  • @Sumer 是的,它会起作用 - foo 对象 inherits 来自原型,因此您可以访问其上的 .constructor 属性。
猜你喜欢
  • 2015-12-03
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多