views:

586

answers:

5

I have been programming with OOP languages for over 10 years but I'm learning JavaScript now and it's the first time I've encountered prototype-based inheritance. I tend to learn fastest by studying good code. What's a well-written example of a JavaScript application (or library) that properly uses prototypal inheritance? And can you describe (briefly) how/where prototypal inheritance is used, so I know where to start reading?

+9  A: 

I would take a look at YUI, and at Dean Edward's Base library: http://dean.edwards.name/weblog/2006/03/base/

For YUI you can take a quick look at the lang module, esp. the YAHOO.lang.extend method. And then, you can browse the source of some widgets or utilities and see how they use that method.

Roland Bouman
+1 for Dean's Base.js
Pete Duncanson
+3  A: 

There's also Microsoft's ASP.Net Ajax library http://www.asp.net/ajax/

There are a lot of good MSDN articles around that as well including this one

http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

Kevin Jones
That is a nice article, thanks!
Roland Bouman
+11  A: 

Douglas Crockford has a nice page on Javascript Prototypal Inheritance:

Five years ago I wrote Classical Inheritance in JavaScript. It showed that JavaScript is a class-free, prototypal language, and that it has sufficient expressive power to simulate a classical system. My programming style has evolved since then, as any good programmer's should. I have learned to fully embrace prototypalism, and have liberated myself from the confines of the classical model.

Dean Edward's Base.js, Mootools's Class or John Resig's Simple Inheritance works are ways to do classical inheritance in Javascript.

Gregory Pakosz
+2  A: 

I suggest looking at PrototypeJS' Class.create:
Line 83 @ http://prototypejs.org/assets/2009/8/31/prototype.js

Tomasz Durka
A: 

The best examples I've seen are in Douglas Crockford's Javascript The Good Bits (I'll update this answer with examples when I have the book to hand). It's definitely worth buying to help you get a balanced view on the language.

Douglas Crockford's is responsible for the JSON format and works at Yahoo as a Javascript guru.

Chris S
responsible? that sounds almost like "guilty of" :)
Roland Bouman
@Roland I think JSON is quite a nice non-verbose format for storing data. He definitely didn't invent it though, the format was there for the config settings in Steam back in 2002
Chris S
Chris S, I think so too - More and more often I wish we could've all skipped XML as exchange format and moved on the JSON right away.
Roland Bouman
Not much to invent: JSON is a subset of JavaScript's own object literal syntax, which has been in the language since around 1997.
Tim Down
@Time good point - I didn't realise it's been there since the start
Chris S
Not quite the start: I think object literals first appeared in Netscape 4, which came out in 1997, while Netscape 2 was the first browser to support JavaScript in 1995.
Tim Down