I spent a good half hour writing an answer to a question on Quora today and I thought it was good enough to qualify as a blog post. The question was How do you implement object orientation in JavaScript?
I’ll be honest, I was a little disappointed by the answers posted prior to mine, however that just fueled the fire and gave me good reason to thoroughly and properly answer the question. As always, I like to let the code do the most talking.
This was the answer I posted:
The real answer is JavaScript IS object oriented already, without any “help” from libraries. It seems that most developers simply don’t get it, and cannot get past the concept of traditional “Classes”. Javascript is a prototypal, object oriented, instance based programming language. In JavaScript, everything is an object that can have properties and methods (sounds familiar, right? maybe like… “classes”?). Behavior and characteristic reuse is accomplished by extending, or “decorating” an existing object; the existing object serves as a “blueprint” or more literally, a prototype.
In JavaScript, traditional classes do not exist, however the equivalent is surprisingly simple and straight forward, all you need is a function(){}:
To be really, really picky…
The “class” or object instance can be extended/decorated:
The “class” or object instance can be inherited:
As you can see, JavaScript doesn’t need any libraries to “implement object orientation”, as it is VERY capable on its own.
If you want to play with this code, I’ve posted a Gist at Github: http://gist.github.com/553982
Edit Thanks to Dmitry for reminding me of his excellent resource
This entry was posted by (@rwaldron) on August 27, 2010 in JavaScript and OOP.
Comments