Home  >  Article  >  Web Front-end  >  Parasitic inheritance of JS inheritance

Parasitic inheritance of JS inheritance

小云云
小云云Original
2018-03-07 10:50:582120browse

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.

1. An example

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.

2. Doubtful point: What is the difference between this method and prototype inheritance Object.create(o)?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn