1. Write a prototype chain inheritance
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function() {
return this.property;
}
function SubType() {
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function() {
return this.subproperty;
}
var instance = new SubType();
console.log(instance.getSuperValue()); // true
2. Write a combined inheritance
function SuperType(name) {
this.name = name;
}
SuperType.prototype.sayName = function() {
alert(this.name);
}
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
alert(this.age);
}
The following two steps can also be equivalent:
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype = Object.create(SuperType.prototype)
There are actually three steps implemented internally:
- Create an object:
var prototype = object(SuperType.prototype);
- Enhanced object:
prototype.constructor = SubType;
- Designated object:
SubType.prototype = prototype;