Reputation: 7012
JavaScript object created with a prototype maintains "live" connection to its prototype, so that changing the prototype also affects the objects created from it.
The semantics of the language would be much simpler if newly created object just copied everything from the prototype and then forgot about it. The actual underlying implementation could be smarter, of course.
Is this feature of live/dynamic connection actually used in some well known JavaScript library or program?
EDIT: I'm not proposing JS inheritance system is flawed, I just want to understand the benefits of aforementioned feature.
Upvotes: 1
Views: 391
Reputation: 5963
This dynamism is present in polyfill libraries that patch older browsers, e.g. by adding Array.prototype.map
, or add upcoming new features from ES6, e.g. Array.prototype.find
. See https://github.com/paulmillr/es6-shim/ for an example.
Upvotes: 0
Reputation: 664423
Surely. I think the most prominent use of this feature is the dynamical adding of methods to the jQuery prototype (called "plugins"), which is exposed as jQuery.fn
.
I can't understand why you think "the semantics of the language would be much simpler if newly created object just copied the prototype properties". Why would that be simpler? You can create objects with that method, using a extend()
function, but that knocks the concept of prototypical inheritance on the head.
It is one of the core features to have that non-static inheritance in Javascript. It is useful to modify the prototype object of already generated instances for:
Upvotes: 5
Reputation: 53
In a talk recently Brendan Eich describe Javascript of being a "target" language which makes it possible for libraries like Jquery or CoffeeScript to be written on top of it, libraries prototype are used to expose commonly used functions and methods faster, look inside a javascript game framework for great examples of prototypes
Upvotes: 0