JS new.target与instanceof [英] JS new.target vs. instanceof

查看:98
本文介绍了JS new.target与instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经对Node 6.x中添加的new.target布尔值进行了一些阅读.这是中提供的new.target的简单示例. MDN

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
}

我的问题是:方法实例对new.target有好处吗?我不太清楚这两者. new.target可能更易于阅读,但这仅是因为它的一组parens ()少了.

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!

推荐答案

使用此Foo实例,您将检查此实例是否为Foo,但不能确保使用. 我可以做这样的事情

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"); 

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

And will work fine. Using new.target you can avoid this issues. I suggest you to read this book https://leanpub.com/understandinges6/read

这篇关于JS new.target与instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆