Let's talk about the javascript code reuse mode and javascript code reuse.
Code reuse has a well-known principle proposed by GoF: Object combination is preferred, rather than class inheritance. In javascript, there is no class concept, so code reuse is not limited to class inheritance. Many methods are used to create objects in javascript. constructors can use new to create objects and modify objects dynamically. There are also many methods to reuse javascript non-class inheritance (which can be called the modern inheritance mode). For example, you can use other objects to combine them into the required objects, and the object blending technology is used, borrow and reuse the required methods.
Class inheritance mode-Default Mode
Example of two constructor Parent and Child:
Copy codeThe Code 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 inheritance function inherit:
Copy codeThe Code is as follows:
Function inherit (C, P ){
C. prototype = new P ();
}
Here, the prototype attribute should point to an object rather than a function. Therefore, it must point to an instance created by the parent constructor rather than the constructor itself.
After that, when a Child object is created, its features are obtained from the Parent instance through the prototype:
Copy codeThe Code is as follows:
Var kid = new Child ();
Kid. say (); // "Adam"
Call the inherited prototype chain:
Add the attributes of the kid:
Copy codeThe Code 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 attributes, so you don't need to search for the prototype chain.
The disadvantage of using the above mode is that it inherits the attributes of two objects at the same time, that is, the attributes added to this and the prototype attributes. Most of the time, you do not need these attributes.
Another disadvantage is that using inherit () Inheritance does not support passing parameters to subconstructors. For example:
Copy codeThe Code is as follows:
Var s = new Child ("Seth ");
S. say (); // "Adam"
This result is not expected. Although the Sub-constructor can pass parameters to the parent constructor, this inheritance mechanism must be re-executed every time a sub-object is required, the efficiency is low because the parent object will be re-created.
This article is here, and we will continue to update the remaining javascript code reuse modes in the future.