js継承に関する手書き

1.プロトタイプチェーンの継承を記述する

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.結合された継承を書く

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);
}

次の2つの手順も同等です。

SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype = Object.create(SuperType.prototype)

内部的に実装されている実際のステップは3つあります。

  1. オブジェクトを作成します。var prototype = object(SuperType.prototype);
  2. 拡張オブジェクト:prototype.constructor = SubType;
  3. 指定されたオブジェクト:SubType.prototype = prototype;

おすすめ

転載: blog.csdn.net/weixin_43912756/article/details/108326789
おすすめ