Sunday, February 19th, 2006
Show Love to the Object Literal
<>p>A Javascript tip from Chris Heilmann, who reckons the object literal is "pretty close to sliced bread". Replace:-
-
var commonSense=null;
-
var standardsCompliance="50%";
-
function init(){
-
// code
-
}
-
function doStuff(){
-
// code
-
}
-
function doMoreStuff(){
-
// code
-
}
-
with the object literal form:
-
-
awesome={
-
commonSense:null,
-
standardsCompliance:"50%",
-
init:function(){
-
// code
-
},
-
doStuff:function(){
-
// code
-
},
-
doMoreStuff:function(){
-
// code
-
}
-
}
-
He's noticed that newer tutorials are tending to use the object literal form, and that object literals are one of several techniques to avoid name clutter:
- Dont use generic names in your scripts (which is a shame as
initandvalidatedoes what it says on the tin)- Add a name to each of the functions like
easyFameAndFortune_initandeasyFameAndFortune_validate- Turn the functions into methods and the variables into parameters of an object
Some libraries go further and offer functions that have to be new()'d to form an object, but if you all you want is a separate namespace, a singleton object literal is a good way to go.








I personally hate object literal notation. The following feels more natural and it’s possible to add classes, objects and members to existing objects and namespaces:
instance:
var awesome = new Object();
awesome.commonSense=null;
awesome.standardsCompliance="50%";
awesome.init = function (){
// code
}
awesome.doStuff = function(){
// code
}
awesome.doMoreStuff = function(){
// code
}
class definition
function awesome()
{
//constructor
}
awesome.prototype.commonSense=null;
awesome.prototype.standardsCompliance="50%";
awesome.prototype.init = function (){
// code
}
awesome.prototype.doStuff = function(){
// code
}
awesome.prototype.doMoreStuff = function(){
// code
}
add object instance or class definition to an existing namespace, class definition or object instance
namespace.awesome = ....
classDefinition.awesome = ...
objectInstance.awesome = ...
test
Hmm… it has been over 15 years since I last programmed Eiffel, but this surely looks like the way Eiffel handles stuff…….
> I personally hate object literal notation.
I personally like Object literals, for they ease programming and maintenance very much.
> The following feels more natural and it’s possible to add classes, objects and members
> to existing objects and namespaces:
> instance:
> [...]
> class definition
Probably some people will never understand that the programming language they are dealing with uses in fact prototype-based, not class-based inheritance; that there are no namespaces, classes, members, and instances there, but only objects with different properties.
And non sequitur. Both forms of object definition can of course be combined sucessfully:
function Prototype()
{
// initialization
}
Prototype.prototype = {
// protoype object property definitions
};
Prototype.prototype.constructor = Prototype;
var p = new Prototype(42);
// See also the “scripts” section on my Website.
PointedEars
It wasn’t more than a day later that I had released my article on JSON for the masses which had been brewing in the mix for about a month which talks about this very same thing.
I basically just wrote this explanation for my upcoming book with Apress on Usable JavaScript. One of the editors got very confused by my examples and asked me to make it more obvious what the OL is.
Cool to see it getting that much referencing.
Dustin, I commented on your article, as JSON and the OL are not the same. If you add this difference – one is code syntax, the other is a data format – then it’ll be a really good resource going deeper than mine :)
I second Hermann Klinke about using instance or prototype definitions.
Object literals are actually hard to maintain. It tries to mimic classes but these ‘:’ and ‘,’ just get confusing when the code grows.
[...] Ajaxian – Show Love… [...]
Phillippe, If you only need one instance, my default choice would be an object literal. Sometimes a background in Java/C++/etc encourages people to think about “I create the metadata, then I create instances of it”, but a language like JS has idioms like OL that IMO are more direct, less clutter, if all you need is a singleton or an isolated namespace for a collection of functions.
PointedEars: “Probably some people will never understand that the programming language they are dealing with uses in fact prototype-based, not class-based inheritance; that there are no namespaces, classes, members, and instances there”
I do understand that javascript is prototype based, but most people do not and I like to think in terms of namespaces, classes, members and instances because I am more familiar with it and there is nothing wrong in thinking in a more abstract way. It’s just a mental representation. You can also simulate class based inheritance. I’ve developed a framework in javascript that makes javascript completely object ortiened with namespaces, classes, enums, events, properties, interfaces that can be private, protected, public, static, internal and you can override and overload methods,you can create methods with strongly typed arguments and you have private, protected, public, static, internal methods.
More importantly, can anyone please compare any possible drawbacks of the above methods (plain, object literal, and class definition) in regards to memory usage/leakage, processing and overall efficiency?
Thanks.
I personally love JSON/object literal notation, and my only problem with it was how to implement things such as classes, inheritance, public and private methods in a way thats consistent with object literal notation.
I have now solved this in a way I’m happy with – http://www.thomasfrank.se/classy_json.html
Here is a practical example of using an object literal. The script creates a div section to write messages on.
http://jdev.blogsome.com/2006/07/11/debug-not-quite-javascript-2/
ê¿ˆì´ ìžˆëŠ” ë‹¹ì‹ ì˜ ë„ì „ì„ ê¸°ë‹¤ë¦½ë‹ˆë‹¤.
무ìžë³¸ìœ¼ë¡œ 수백만ì›ëŒ€ì˜ ì›” ì•ˆì •ìˆ˜ìž…ì„ í™•ë³´í• ìˆ˜ 있는 ì‚¬ì—…ì„ ì†Œê°œí•©ë‹ˆë‹¤.
♣ 사업 특징.
* 누구나, ìžë³¸íˆ¬ìžê°€ í•„ìš” 없어 ì†í•´ 보는 ì¼ ì—†ëŠ” 윈윈-사업.
* 장기 ì•ˆì •ìˆ˜ìž… 확보와 ë…¸í›„ëŒ€ì±…ì— ì 합한 투잡(부업).
* í™•ë³´ëœ ì•ˆì •ìˆ˜ìž…ì€ ì¼ìƒ 지급ë˜ê³ , ìžë…€ì—게 ìƒì† ë¨.
* í†µì‹ ì‚¬ì—…ë²• ê°œì •ìœ¼ë¡œ ê°œì¸ë„ í• ìˆ˜ 있는 í™©ê¸ˆì•Œì„ ë‚³ëŠ”ë‹¤ëŠ” ê¿ˆì˜ ì´ë™í†µì‹ 사업.
* 온/오프ë¼ì¸ í™ë³´ë§Œìœ¼ë¡œ í‰ìƒìˆ˜ìž…누ì !!
* ì¸í„°ë„·ìœ¼ë¡œê°€ëŠ¥í•˜ë¯€ë¡œ ì§€ë°©ì— ê³„ì‹ ë¶„ë„ ì‚¬ì—…í™œë™ì— 지장 없는 ì „êµê·œëª¨ 사업.
* ì¸í„°ë„· 사업용 홈페ì´ì§€(투잡ok) 무료 ë¶„ì–‘.
♣ ì‚¬ì—…ë‚´ìš©ì€ í™ˆíŽ˜ì´ì§€ì˜ ì—서 ìƒì„¸ížˆ 들으실 수 있습니다.
* ì—°ë½ ì£¼ì‹œë©´ ì„±ì‹¬ê» ë•ê² ìŠµë‹ˆë‹¤.
* 홈페ì´ì§€ì— ì €ì˜ ì„±ëª…ê³¼ ì—°ë½ì²˜ê°€ 있습니다.
* ìžë³¸íˆ¬ìž ì—†ì´ ë‚´ ë…¸ë ¥ìœ¼ë¡œ ì¼ìƒì˜ ì•ˆì •ìˆ˜ìž…ì„ í™•ë³´í• ìˆ˜ 있는 ì ˆí˜¸ì˜ ê¸°íšŒ!
* 본사홈피: http://ceoit.co.kr/web/king098/
* 비번1111 í—ˆë½ì—†ì´ ê¸€ì˜¬ë ¤ì„œ 죄송합니다.
* 등ë¡ì„ ì›í•˜ì§€ 않ì„경우url주소를 ìƒê¸° ë©”ì¼ë¡œ 보내주시면
다시는 올리지 ì•Šê² ìŠµë‹ˆë‹¤.
Thanks lot of help provided
http://students.50webs.org
http://vpn.50webs.org
how do you do {“str”+var:val}. seems to be a syntax error!
Oh my god, that looks like Eiffel! Am I right or let the time the memories of Eiffel vanish?
On a related issue, how do you have multiple child objects of a parent object? Consider the code below:
var parent={
childCount: 0,
child: {
id:false,
init: function() {
alert(this.id);
parent.childCount++;
this.id = parent.childCount;
alert(“Child ” + this.id + ” Created”);
}
}
}
Calling ‘parent.child.init();’, the first alert produces ‘undefined’ and the second ‘Child 1 Created’. A second call to ‘parent.child.init();’ produces the ’1′ from above instead of the ‘undefined’ I’m expecting – I realise this is because I’m working with the same object.
However, calling ‘var firstChild = parent.child.init(); var secondChild = parent.child.init()’ produces the same result (as does ‘var firstChild = parent.child; firstChild.init();).
I’ve also tried the ‘new’ operator. But the code ‘var firstChild = new parent.child;’ produces the error ‘parent.child is not a constructor’.
How is this supposed to work?