JavaScript does not contain traditional class inheritance models, but uses prototypal prototype models.
JavaScript does not contain the traditional class inheritance model, but uses the prototypal prototype model.
Although this is often mentioned as a disadvantage of JavaScript, prototype-based inheritance models are more powerful than traditional class inheritance models. It is easy to implement the traditional class inheritance model, but it is much more difficult to implement prototype inheritance in JavaScript. (It is for example fairly trivial to build a classic model on top of it, while the other way around is a far more difficult task .)
Since JavaScript is the only language widely used based on prototype inheritance, it takes some time to understand the differences between the two inheritance modes.
The first difference is that JavaScript uses the Inheritance Method of prototype chain.
Function Foo () {this. value = 42;} Foo. prototype = {method: function () {}}; function Bar () {}// set the prototype attribute of Bar to the Instance Object Bar of Foo. prototype = new Foo (); Bar. prototype. foo = 'Hello NowaMagic '; // modify Bar. prototype. constructor is the Bar itself. prototype. constructor = Bar; var test = new Bar () // create a new instance of Bar
Simply using Bar. prototype = Foo. prototype will cause two objects to share the same prototype. Therefore, changing the prototype of any object affects the prototype of another object. In most cases, this is not the expected result.