Friday, February 11, 2011

Inheritance and JavaScript

I am working on a project using JavaScript and I needed to use Inheritance. I didn't know it is not part of the language itself. Since ActionScript and JavaScript both are based on ECMA standards and ActionScript got classes & inheritance I thought JavaScript might have it as well.

Anyway long story short, here are some of the links I found to be very useful in implementing inheritance logic. I did a mix of few, but main chunk is still from Kevin's snippet.

http://kevlindev.com/tutorials/javascript/inheritance/index.htm
http://ejohn.org/blog/simple-javascript-inheritance/
http://www.crockford.com/javascript/inheritance.html

I really like John Resig's solution, it's clever and provides some great features like the use of _super.method() only available inside the child class method. And I like how he uses JavaScript closure to his advantage. His solution also allows to call the parent class constructor automatically, but he delegates all the constructor work to init() function so you can get flexibility of calling it when you want while skipping it during the inheriting process (read his post for details).

Douglas Crockford has great explanation of different kinds of inheritance in JavaScript and how to achieve it with his own implementation of inheritance utility. He makes some excellent points about JavaScript's features.

Kevin's solution is the simplest yet works great. The neat trick he uses is to create a temporary object to transfer the prototype members to the subclass. This gives you the control to call parent constructor when you want inside the subclass constructor.

Programming many things at the same time is already complicated enough and so any solution that is simpler is the best for me. So went with Kevin's solution in the end.

No comments:

Post a Comment