是JavaScript的“新”吗?关键字被视为有害 [英] Is JavaScript's "new" keyword considered harmful?

查看:98
本文介绍了是JavaScript的“新”吗?关键字被视为有害的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个问题中,用户指出 new 关键字使用起来很危险,并提出了一个不使用 new 的对象创建解决方案。我不相信这是真的,主要是因为我使用了Prototype,Scriptaculous和其他优秀的JavaScript库,并且每个人都使用 new 关键字。

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new. I didn't believe that was true, mostly because I've used Prototype, Scriptaculous and other excellent JavaScript libraries, and everyone of them used the new keyword.

尽管如此,昨天我在YUI剧院观看道格拉斯·克罗克福德的谈话,他说的完全一样,他没有使用 new 关键字再次出现在他的代码中( Crockford on JavaScript - Act III:Function终极 - 50:23分钟)。

In spite of that, yesterday I was watching Douglas Crockford's talk at YUI theater and he said the exactly same thing, that he didn't use the new keyword anymore in his code (Crockford on JavaScript - Act III: Function the Ultimate - 50:23 minutes).

使用是否不好关键词?使用它的优点和缺点是什么?

Is it 'bad' to use the new keyword? What are the advantages and disadvantages of using it?

推荐答案

Crockford在推广优秀的JavaScript技术方面做了很多工作。他对语言关键要素的看法立场引发了许多有益的讨论。也就是说,有太多的人把每一个坏或有害的宣言当作福音,拒绝超越一个人的意见。有时可能会有点令人沮丧。

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

使用 new 关键字提供的功能有几个优点从头开始构建每个对象:

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:


  1. Prototype inheritance 。虽然习惯于基于类的OO语言的人经常看到混合的怀疑和嘲笑,但JavaScript的本机继承技术是一种简单且令人惊讶的有效的代码重用方法。新关键字是使用它的规范(并且只有可用的跨平台)方式。

  2. 性能。这是#1的副作用:如果我想为我创建的每个对象添加10个方法,我可以只写一个创建函数,手动将每个方法分配给每个新对象......或者,我可以将它们分配给创建函数的原型,并使用 new 来标记新对象。这不仅更快(原型上的每个方法都不需要代码),它避免了为每个方法使用单独的属性来膨胀每个对象。在较慢的机器上(或者尤其是较慢的JS解释器),当创建许多对象时,这可以显着节省时间和内存。

  1. Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  2. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

是的, new 有一个关键的缺点,由其他答案巧妙地描述:如果你忘记使用它,你的代码将在没有警告的情况下破解。幸运的是,这个缺点很容易减轻 - 只需向函数本身添加一些代码:

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
}

现在您可以享受 new 的优势,而无需担心因意外误用而导致的问题。你甚至可以在检查中添加一个断言,如果破坏代码的思想默默地工作困扰你。或者,当某些评论时,使用检查来引入运行时异常:

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");

(请注意,此代码段能够避免硬编码构造函数名称,与以前不同例如,它不需要实际实例化对象 - 因此,它可以不经修改地复制到每个目标函数中。)

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig详细介绍了这种技术简单的类实例化帖子,以及将此行为构建到你的班级默认。绝对值得一读...正如他即将出版的书, JavaScript忍者的秘密,它发现隐藏JavaScript中的黄金以及JavaScript语言的许多其他有害功能( 对于我们这些最初解雇此问题的人来说尤其具有启发性备受诟病的特征作为噱头)。

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

这篇关于是JavaScript的“新”吗?关键字被视为有害的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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