Parasitic (parasitic) inheritance is a thought that is closely related to prototype inheritance.
The idea of parasitic inheritance is similar to parasitic constructors and factory patterns (the parasitic constructors and factory patterns mentioned here are all methods of creating objects, and there is time to write a blog), which is to create a function that encapsulates the inheritance process , which in some way enhances the object internally. And finally again like really it did all the work like returning objects.
Or use the previous object function:
function Object (o) { function F () {} f.prototype = O; return new F ();
The following code demonstrates parasitic inheritance.
function Createanother (original) { var clone = object (original); Create a new object by calling the function object clone.sayhi = function () { //In some way to enhance the object alert ("HI"); }; return clone; return this object}
In this example, the Createanother () function takes a parameter, which is the object that will be the basis of the new object. It then passes the object (original) to an object () function and assigns the returned result to clone. At this point, the instance properties and instance methods of original become the prototype properties and prototype methods of the Clone object. Next, add a new method Sayhi () to the Clone object, and finally return to the Clone object. You can use the Createanother () function as follows.
var person = { name: ' Nico ', friends: ["Shelby", "Court", "Van"]};var Anotherperson = Createanother (person); Anotherperson.sayhi (); ' Hi '
The above code returns a new object--anotherperson based on person. The new object not only has all the properties and methods of person (the attributes and methods of the person are added to the Anotherperson prototype object), but also has its own sayhi () method.
Parasitic inheritance is also useful in situations where objects are primarily considered rather than custom types and constructors. The object () function used in the previous demonstration of inheritance mode is not required. Any function that can return a new object applies to this pattern.
However, by using parasitic inheritance to add functions to an object, the efficiency is reduced due to the lack of function reuse. This is similar to a constructor function.
Inherited parasitic inheritance in JavaScript