Objectifying JavaScript

My latest column over at Digital Web has gone live. Entitled Objectifying JavaScript, I cover various approaches to creating objects in JavaScript and why you might use one approach over another.

Published September 19, 2006
Categorized as Writing
Short URL: https://snook.ca/s/671


6 Comments · RSS feed
Anthony said on September 19, 2006

informative stuff, and useful too.

Daniel Lemire said on September 19, 2006

This is precisely what I have been looking for. Thanks for sharing this practical information with the developer community at large.

Jesus said on September 26, 2006

Very nice article.

zhanghao from china said on February 16, 2007

At first ,thanks for your article. but I don't agree with your point in chapter Prototype,"In short, a call to a property of an object first checks the object itself for the property; if it doesn’t exist, it’ll check it’s template’s prototype; we’ll only have one version of the property stored in memory, no matter how many objects we create." .I tested it with the following code:
function Animation(){
this.ID = "123";
var A = new Animation();
var B = new Animation();
Animation.prototype.Name = "AAA";
alert(A.Name+" "+B.Name);
A.Name = "foo";
alert(A.Name+" "+B.Name);

If we only have one version of the property "Name",then when I change the A.Name="foo",the B.Name will equal to "foo" too. isn't it? But it's not. however the B.Name="AAA".obviously,there are not only one version of the "Name" property exist. I think that the prototype's property or method will copy to every object,not keep one version.

Jonathan Snook said on February 16, 2007

@zhanghao: in your example, you're making a change to the 'A' object, assigning it a 'Name' property. That means it no longer checks the Animation prototype property 'Name'.

Basically, prototypal inheritance means it checks the current object first for a property and if it can't find it, it looks to the prototype to find it. This let's us override prototype methods and properties at the object level.

Hopefully that clears things up a little.

zhanghao from china said on February 17, 2007

thanks for your explanation Jonathan.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.