JavaScript object created with a prototype maintains \"live\" connection to its prototype, so that changing the prototype also affects the objects created from it.
T
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:
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
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.