1. Escribe un prototipo de herencia de cadena
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. Escribe una herencia combinada
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);
}
Los dos pasos siguientes también pueden ser equivalentes:
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype = Object.create(SuperType.prototype)
En realidad, hay tres pasos implementados internamente:
- Crea un objeto:
var prototype = object(SuperType.prototype);
- Objeto mejorado:
prototype.constructor = SubType;
- Objeto designado:
SubType.prototype = prototype;