The previous article has introduced combination inheritance, and now we will talk about the remaining inheritances.
Prototype inheritance
Call a function and receive the object returned by this function. The prototype of this object is the parameter object passed to the function.
like:
function personObject(o){ function F(){} F.prototype = o; return new F();}var person = { name: "Nicholas", friends: ["Shelby", "Court", "Van"]}var person_one = personObject(person);From the above code, we know that person is the prototype of person_one. ES5 has added a method to normalize prototype inheritance. This method is Object.create(). This method has two parameters. The first is an object as the prototype of the new object, like the person above, and the second is an object that defines additional attributes for the new object. The second parameter is optional.
like:
var person_one = Object.create(person, { name: { value:"Jon" }});When you just want to keep one object similar to another, you can use prototype inheritance.
Parasitic inheritance
Implement prototype inheritance in a function, and then add your own properties and methods to the received object.
like:
function createAnother(o){ var person_one = personObject(o); person_one.sayHi = function(){ alert(" hi "); } return person_one;}Parasitic combination inheritance
Combination inheritance also has its disadvantages. It implements two attribute inheritance, and parasitic combination inheritance avoids this problem. Instances inherit attributes through constructors, while the prototype method is inherited through parasitic inheritance.
like:
function inherit(subType, superType){ var prototype = Object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype;}By calling the above function, the prototype of subTye.prototype is superType.prototype, which completes the inheritance of the prototype method.
The above javascript analysis on inheritance is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.