Home >Web Front-end >JS Tutorial >Parasitic inheritance of JS inheritance
It is easy to feel intimidated when hearing the term "parasitic inheritance". What is this? Don't worry, this article will try to explain this inheritance method in JS in an easy-to-understand way, and I hope it can help everyone.
We first define an empty function, the formal parameter is original, like the following:
function createAnother(original){}
Create a new object clone in this function:
function createAnother(original){ var clone=Object.create(original); }
Add the attribute sayHi to the clone object. The sayHi attribute is a function:
function createAnother(original){ var clone=Object.create(original); clone.sayHi=function(){ alert('hi'); }; }
Finally, return the clone object:
function createAnother(original){ var clone=Object.create(original); clone.sayHi=function(){ alert('hi'); }; return clone; }
Suppose we have such an object:
var person={ name:'Nicholas', friends:['Shelby','Court','Van'] };
Pass the above objects as actual parameters into our function to run:
var anotherPerson=createAnother(person); anotherPerson.sayHi();
The result of the operation is: the 'Hi' window will pop up.
We see that the function createAnother has this sentence:
var clone=Object.create(original);
Isn’t this prototypal inheritance?
Indeed, the prototypal inheritance method is indeed used internally, and the final return is the clone object. However, it is still a little different from prototypal inheritance:
Prototypal inheritance inherits the properties of the original object, and the new object does not have new additional properties; parasitic inheritance can add properties to the new object internally, and the new object has the original object in addition to properties, and also has internally added properties.
In the above example, compared to prototypal inheritance, there are additional key statements:
clone.sayHi=function(){ alert('hi'); };
After creating an instance, the instance will have this attribute.
Related recommendations:
Sharing of several js inheritance styles
js inheritance Base class source code analysis_js oriented Object
js inheritance implementation code_javascript skills
The above is the detailed content of Parasitic inheritance of JS inheritance. For more information, please follow other related articles on the PHP Chinese website!