Sunday, February 19th, 2006

Show Love to the Object Literal

Category: JavaScript, Programming

<>p>A Javascript tip from Chris Heilmann, who reckons the object literal is “pretty close to sliced bread”. Replace:

javascript
< view plain text >
  1. var commonSense=null;
  2. var standardsCompliance="50%";
  3. function init(){
  4.   // code
  5. }
  6. function doStuff(){
  7.   // code
  8. }
  9. function doMoreStuff(){
  10.   // code
  11. }

with the object literal form:

javascript
< view plain text >
  1. awesome={
  2.   commonSense:null,
  3.   standardsCompliance:"50%",
  4.   init:function(){
  5.     // code
  6.   },
  7.   doStuff:function(){
  8.     // code
  9.   },
  10.   doMoreStuff:function(){
  11.     // code
  12.   }
  13. }

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 init and validate does what it says on the tin)
  • Add a name to each of the functions like easyFameAndFortune_init and easyFameAndFortune_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.

Related Content:

  • I Love Lucene
    There are a lot of areas on TheServerSide that we would like to change. Trust us. Ever since I joined TheServerSide I have cringed at our search...
  • Love hertz
    From 80286 to Pentium 4, 2900 to Duron, Intel and AMD have always been at the heart of processor...
  • Tough Love
    On the heels of COMMON, consultant and author Brian Kelly offers his own iSeries...
  • Show laptop native apps some love
    Tablets run native apps to improve the user experience, and so should laptops and desktops. Users might not notice the drawbacks of remote desktops on...
  • Firefox still feels the love, despite flaws
    Users love to blast Microsoft over IE flaws. Can Mozilla expect the same...

Posted by Michael Mahemoff at 2:11 am
18 Comments

+++--
3.2 rating from 53 votes

18 Comments »

Comments feed TrackBack URI

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 = ...

Comment by Hermann Klinke — February 19, 2006

test

Comment by nico — February 19, 2006

Hmm… it has been over 15 years since I last programmed Eiffel, but this surely looks like the way Eiffel handles stuff…….

Comment by Barry Nauta — February 19, 2006

> 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

Comment by PointedEars — February 19, 2006

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.

Comment by Dustin Diaz — February 19, 2006

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 :)

Comment by Chris Heilmann — February 20, 2006

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.

Comment by Philippe — February 20, 2006

[...] Ajaxian – Show Love… [...]

Pingback by randomcat.co.uk » Blog Archive » Javascript Object Notation — February 20, 2006

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.

Comment by Michael Mahemoff — February 20, 2006

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.

Comment by Hermann Klinke — February 20, 2006

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.

Comment by Señor Pantaloons — February 20, 2006

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

Comment by Thomas Frank — June 18, 2006

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/

Comment by Erik — July 24, 2006

꿈이 있는 당신의 도전을 기다립니다.

무자본으로 수백만원대의 월 안정수입을 확보할 수 있는 사업을 소개합니다.

♣ 사업 특징.

* 누구나, 자본투자가 필요 없어 손해 보는 일 없는 윈윈-사업.

* 장기 안정수입 확보와 노후대책에 적합한 투잡(부업).

* 확보된 안정수입은 일생 지급되고, 자녀에게 상속 됨.

* 통신사업법 개정으로 개인도 할 수 있는 황금알을 낳는다는 꿈의 이동통신사업.

* 온/오프라인 홍보만으로 평생수입누적!!

* 인터넷으로가능하므로 지방에 계신 분도 사업활동에 지장 없는 전국규모 사업.

* 인터넷 사업용 홈페이지(투잡ok) 무료 분양.

♣ 사업내용은 홈페이지의 에서 상세히 들으실 수 있습니다.

* 연락 주시면 성심껏 돕겠습니다.

* 홈페이지에 저의 성명과 연락처가 있습니다.

* 자본투자 없이 내 노력으로 일생의 안정수입을 확보할수 있는 절호의 기회!

* 본사홈피: http://ceoit.co.kr/web/king098/

* 비번1111 허락없이 글올려서 죄송합니다.

* 등록을 원하지 않을경우url주소를 상기 메일로 보내주시면

다시는 올리지 않겠습니다.

Comment by 도우미 — July 26, 2006

Thanks lot of help provided

http://students.50webs.org
http://vpn.50webs.org

Comment by hammad — January 1, 2007

how do you do {“str”+var:val}. seems to be a syntax error!

Comment by ix — June 10, 2007

Oh my god, that looks like Eiffel! Am I right or let the time the memories of Eiffel vanish?

Comment by Matthew — July 8, 2007

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?

Comment by Iain Porter — October 18, 2007

Leave a comment

You must be logged in to post a comment.