Handwriting about js inheritance

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:

  1. Create an object:var prototype = object(SuperType.prototype);
  2. Enhanced object:prototype.constructor = SubType;
  3. Designated object:SubType.prototype = prototype;

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108326789