面向对象之寄生组合继承

最近在使用面向对象编程,发现原型继承和构造函数继承的组合还是有点小缺陷,于是乎又把JS高级程序设计第六章面向对象又看了一遍,发现寄生组合继承确实挺好,就分享给大家。

function object( o ) {
  function F () {};
  F.prototype = o;
  return new F()
};

function inheritPrototype ( SubType, SupType ) {
  var prototype = object ( supType.prototype );
  prototype.constructor = SubType;
  SubType.prototype = prototype;
};

function SupType ( name ) {
  this.name = name;
  this.friends = [ "a", "b", "c" ];
};

SupType.prototype.sayName = function () {
  alert( this.name );
};

function SubType ( name, age ) {
  SupType.call( this, name );
  
  this.age = age;
};

inheritPrototype( SubType, SupType );

SubType.prototype.sayAge = function () {
  alert(  this.age );
};


猜你喜欢

转载自blog.csdn.net/Deng_gene/article/details/70167840