There is a famous principle for code reuse, proposed by GoF: give priority to object composition rather than class inheritance. In JavaScript, there is no concept of classes, so code reuse is not limited to class inheritance. There are many ways to create objects in JavaScript. There are constructors, you can use new to create objects, and you can dynamically modify objects. JavaScript's non-class inheritance (which can be called the modern inheritance model) also has many reuse methods, such as using other objects to combine into the required objects, object mixing technology, borrowing and reusing the required methods.
Class inheritance mode-default mode
Examples of two constructors Parent and Child:
The following is an implementation method of the reusable inheritance function inherit():
The prototype attribute here should point to an object, not a function, so it must point to an instance created by the parent constructor, not to the constructor itself.
After this, when the Child object is created, its functions will be obtained from the Parent instance through the prototype:
The prototype chain after calling inheritance:
Add further attributes of kid:
Changes in the prototype chain:
You can find the name in the properties of your own object, so you don’t have to look up the prototype chain.
One of the disadvantages of using the above pattern is that the attributes of two objects are inherited at the same time, namely the attributes added to this and the prototype attributes. Most of the time, these properties of its own are not needed.
Another disadvantage is that using inherit() inheritance does not support passing parameters to sub-constructors, for example:
This result is not expected. Although the child constructor can pass parameters to the parent constructor, this inheritance mechanism must be re-executed every time a child object is needed, and it is inefficient because in the end The parent object will be recreated.
This article ends here. We will continue to update the other modes of JavaScript code reuse mode in the future.