简体   繁体   中英

Why most of the javascript frameworks use object literals

为什么大多数javascript框架都使用对象常量而不是构造函数或带有原型的构造函数?如果有人在新框架中使用带有原型的构造函数,它将是非标准的。对象常量比带有原型的构造函数有什么优势?

I assume you mean how jQuery automatically defines the jQuery/$ objects? simple answer ... it's easier that way. Can you imagine how confusing jQuery would be for new users if they had to include the following two lines in every single page?

var jQuery = new jQuery();
var $ = jQuery;

I think you're talking about using {} vs new Object() and [] vs new Array() .

The literal version in both cases is often faster (of course this depends on the browser). You also get the added advantage of being able to define properties in an object or items in an array from the onset. This makes the code more lightweight and readable.

var o = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
// vs.
var o = new Object();
o.a = 1;
o.b = 2;
o.c = 3;
o.d = 4;

var a = [1, 2, 3, 4, 5];
// vs.
var a = new Array();
a.push(1, 2, 3, 4, 5);

Edit : I made performance tests for objects and arrays . For me, object literals were actually a bit slower in Chrome. Array literals were much faster, however. The syntax is still preferred, though.

It all depends on the need of the programme you're writing and the way you want to maintain the code base.

When you have objects which get instantiated a lot with shared properties and methods it could be more efficient memorywise to use a constructor and fill its prototype.

When the code is more or less a singleton it is probably more efficient to just make an object and fill it with some methods.

If you would like more information about "patterns" and what they can mean to you you could check out http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Or if you like a regular (e-)book i would recommend http://shop.oreilly.com/product/9780596806767.do

But if your instantiating the object several times then prototype uses less memory because you're not recreating the entire object with all its methods.

Prototype is nice because it allows you to create a new method on the fly and have all intances of that object use. Syntactically it's ugly and I prefer object literal. But if you're building a massive app and performance is a big issue then prototype is probably the way forward no?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM