composition inheritance

function SuperType(name){
 this.name = name;
 this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
 alert(this.name);
};
function SubType(name, age){
 // inherit properties
 SuperType.call(this, name);

 this.age = age;
}
//Inherit method
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
 alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
var instance2 = new SubType("Greg", 27);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"Greg";
instance2.sayAge(); //27

 In this example, the SuperType constructor defines two properties: name and colors. The prototype of SuperType defines a method sayName(). The SubType constructor passes in the name parameter when calling the SuperType constructor, and then defines its own property age. Then, the instance of SuperType is assigned to the prototype of SubType, and the method sayAge() is defined on the new prototype. This allows two different SubType instances to have their own properties -- including the colors property -- and use the same method. Combinatorial inheritance avoids the pitfalls of prototype chains and borrowed constructors, and combines their advantages to become the most commonly used inheritance pattern in JavaScript. Furthermore, instanceof and isPrototypeOf() can also be used to identify objects created based on compositional inheritance.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326173297&siteId=291194637