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:

And in particular:

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:

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:

To learn about the difference between new and Object.create I read this:
and this:


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:

Keine Kommentare: