Friday, June 13, 2014

Fun with JavaScript inheritance

One could say that JavaScript does not support native inheritance for OOP and could not be so wrong. JavaScript happened to be having one of the most powerful OOP I have ever seen :)

Something more, JavaScript does the inheritance trough a prototype chaining, which actually provides even more power than you can imagine.

See the following simple chaining example, that shows a chained inheritance (not the typical one-step prototype->object inheritance everyone knows):

~$ node
> a={}
{}
> b = Object.create(a)
{}
> c = Object.create(b)
{}
> a.test = 1
1
> a
{ test: 1 }
> b
{}
> c
{}
> c.test
1
> b.text=2
2
> b
{ text: 2 }
> b.test
1
> c.test
1
> c.text
2
> c
{}

So now you can see above how can we do a very easy but powerful chain of objects. Something more, that works for ANY object, including chaining BOTH the methods and the prototypes of the objects, so you can modify either the objects directly, or their prototypes and everything is inherited with a two-shadow priority model.

~$ node
> a=[1,2,3,4]
[ 1, 2, 3, 4 ]
> b=Object.create(a)
{}
> b
{}
> b[1]
2
> b.length
4
> b
{}

So now you can see that b is still (an empty) object but has behavior and properties like an array :)

No comments:

Post a Comment