From my experiance, JavaScript does this:
Since I started digging into prototypal inheritance, I would like to know how it is actually used in practice. What are the use cases?
Is anyone here actively using inheritance patterns? What for?
(I understand that there are lots of answers to my question - I just would like to hear some of them to get the feel of using inheritance in JavaScript)
My experience working with jQuery (and JavaScript before it) is that prototypical inheritance isn't as useful as I was expecting. It has uses, but it's not fundamentally important to the language.
In Javascript if you want to return an object with a method foo
:
return {
foo: function() {
alert('You called foo!');
}
};
And callers can treat such objects as polymorphic - that is, they can call foo
without worrying about what "type" of object it is. There is no need for inheritance.
Against this background, prototypes are merely an optimisation. They allow you to create a large number of objects without having to replicate a big set of function properties in each instance. This is why jQuery uses it internally. A jQuery object has dozens of functions, and it might be a major overhead to copy them into every instance.
But from the perspective of a user of jQuery, prototypes aren't particularly important. It could be rewritten to not use them and it would still work (but might use a lot more memory).
As more and more code is written specifically for mobile devices running iOS, Android, et.al, and as the app-paradigm matures, there is a shift towards putting more and more complexity and logic into javascript libraries running on the devices.
The Object/inheritance model of javascript give the developer a very flexible toolkit for developing dynamic and complex applications.
The JavaScript inheritance model lets you:
This is similar to the class and mixin features of ruby, and opens up a ton of new design and inheritance patterns, of only a few has been invented or documented.
jquery is the best example of a mature javascript library. link text prototype and scriptaculus are others.
Douglas Crockford has some interesting articles regarding various inheritance:
http://javascript.crockford.com/inheritance.html
http://javascript.crockford.com/prototypal.html
http://javascript.crockford.com/private.html
The first one is old, and you might not want to do anything that way, but it shows how flexible JavaScript can be. The second is just how he uses prototypes. The last one is just interesting if you are going to use objects much in JavaScript, and it has a bit about inheritance.
Reading them (they're short) may not give you all of the answers you want, but I suspect it will make you think about and see JavaScript in a slightly different way. That said, Crockford is always very confident in his writing, but I don't think you should take his word as law.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With