Dienstag, 29. Januar 2013

On JavaScript inheritance

I have struggled for quite some time to find the right inheritance strategy for me considering all the available blog posts about this topic and the many many different approaches.

After many searches I finally found this stackoverflow post:
http://stackoverflow.com/questions/7486825/javascript-inheritance

And in particular:
http://stackoverflow.com/questions/7486825/javascript-inheritance/10245829

This looked like a very nice approach.

The new thing for me was the D.call(this) idea.
( This solved the problem with the shared matrix attribute from my Spatial class in Spatial child classes.)

This led me to:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

With this information I realized that there was a slight draw back with the new approach:
The class constructors were being called twice.
Once: D.call(this); and again: new D();

This led me to Object.create:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

To learn about the difference between new and Object.create I read this:
http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript
and this:

understanding-the-difference-between-object-create-and-new-somefunction-in-javascript


But the answer in the second link was not accurate as one commenter pointed out. He had a link to the EcmaScript 5 specification: http://es5.github.com/#x15.2.3.5

This made it finally clear and I started to understand these lines in some inheritance examples:
Child.prototype = Object.create(Parent.prototype);

This basically avoids the unneeded call to the constructor.
Here is a complete example:
http://jsfiddle.net/9Dxkb/1/
or:
http://stackoverflow.com/questions/7486825/javascript-inheritance/12816953

Keine Kommentare: