There is a famous principle for code reuse, which was proposed by GoF: priority is used to use object combinations 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, including constructors, you can use new to create objects, and you can dynamically modify objects. There are also many methods for reusing non-classified inheritance (which can be called modern inheritance mode) in JavaScript, such as combining other objects into required objects, object mixing technology, borrowing and reusing required methods.
Classical inheritance mode-default mode
Examples of two constructors Parent and Child:
The code copy is as follows:
function Parent(name){
this.name = name||"Adam";
}
Parent.prototype.say = {
return this.name;
};
function Child(name){
}
inherit(Child, Parent);
The following is an implementation method of the reusable inherit() function:
The code copy is as follows:
function inherit(C,P){
C.prototype = new P();
}
Here the prototype property 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 creating a Child object, it will obtain its functions from the Parent instance through the prototype:
The code copy is as follows:
var kid =new Child();
kid.say();//"Adam"
Call the inherited prototype chain:
Further add the properties of kid:
The code copy is as follows:
var kid = new Child();
kid.name = "Patrick";
kid.say();//"Patrick"
Changes in the prototype chain:
You can find the name in your object properties, so you don’t have to look for the prototype chain anymore.
One of the disadvantages of using the above pattern is that it inherits the properties of two objects at the same time, namely the properties added to this and the prototype properties. Most of the time, these attributes of oneself are not needed.
Another disadvantage is that using inherit() inherit() inherit does not support passing parameters to subconstructors, for example:
The code copy is as follows:
var s = new Child("Seth");
s.say();//"Adam"
This result is not expected. Although the child constructor can pass parameters into the parent constructor, this inheritance mechanism must be re-executed every time a child object is needed, and it is inefficient because the parent object will eventually be re-created.
This article ends here. We will continue to update the remaining modes of the javascript code reuse mode in the future.