Escritura a mano sobre la herencia js

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:

  1. Crea un objeto:var prototype = object(SuperType.prototype);
  2. Objeto mejorado:prototype.constructor = SubType;
  3. Objeto designado:SubType.prototype = prototype;

Supongo que te gusta

Origin blog.csdn.net/weixin_43912756/article/details/108326789
Recomendado
Clasificación