文字符号VS.构造函数在JavaScript中创建对象 [英] Literal notation VS. constructor to create objects in JavaScript

查看:164
本文介绍了文字符号VS.构造函数在JavaScript中创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从基础知识学习JavaScript(尽管我使用其他语言编写,例如C#)。它向我提出了这两种方式中哪种方式更有效并且应该作为一般规则使用的问题。

I am learning JavaScript from the basics (although I program in other languages such as C#). It popped up to me the question of which is of this two ways is more efficient and should be use as general rule.

我确信并期待没有明确的答案,但我想知道一般的利弊。

I am sure and expecting no definitive answer but I would like to know the general pros and cons.

感谢您!!

推荐答案

对象文字通常是要走的路。它们只需在加载脚本时进行解析,这可以通过脚本引擎引入各种优化。

Object literals are usually the way to go. They only need to be parsed when loading the script, which can introduce various optimizations by the scripting engine.

需要执行构造函数。这意味着它们会变慢,但您可以轻松地向它们添加一些验证代码等,并且它们允许构造具有隐藏在构造函数范围内的公共,特权方法和私有属性的复杂对象。此外,他们当然会构建共享原型的对象,您可能会发现这些对象很有用。

Constructors need to be executed. That means they will be slower, but you can easily add some validation code etc. to them, and they allow the construction of complex objects with public, privileged methods and private "attributes" hidden in the constructors scope. Also, they of course construct objects that share a prototype, which you might find useful.

这篇关于文字符号VS.构造函数在JavaScript中创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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