Contructors and Inheritance in Javascript

 

js_inherit

There is a really great article on inheritance in Javascript tucked away in the Rochester Institute of Technology website :

http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/

Dated from 1997 and very hard to find using Google, this article offered me the perfect solution to the problem I had in front of me, namely, having objects with constructors that also use inheritance.

Incorporating constructors in Javascript is usually done using the ‘static’ notation, where one method contains other methods :

Everything between the line :

and the first method would be considered a constructor, and you can add as many parameters as you want to the outer method (in my case it is just one: myInitialData).

The only problem with this technique is that you can’t define the object as being of some other kind of object. In other words you can’t have MyObject be anything else.

Using the dynamic Javascript notation you can create an object to be of something else :

ie. b is an a;

you can also add a constructor-like method, called init().

Example :

If you have something like this, you have inheritance (It inherits Building), and your init() becomes your constructor. But it is not a real constructor because you have to remember to call it after the create. Constructors are a way of forcing the programmer to execute some initial code.

From the above website, the solution would be to set the prototype after defining the method using the first technique :

Using this technique, we have inheritance, ie MyObject is a Building, and we have a constructor too.

This is how we do it now!


Posted in JavaScript | Tagged , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

THREE_COLUMN_PAGE