abp-159,js最理想的繼承——寄生組合式繼承

 // 基於已有對象建立新對象,等於對傳入的對象進行了一次淺複製
 function duplicate(obj){
  var f = function(){};
  f.prototype = obj;
  return new f();
 }app

 // 繼承原型
 function extend(target, obj){
  var proto = duplicate(obj.prototype);
  proto.constructor = target;
  target.prototype = proto;
 }this

 // 超類
 function SuperClass(prop){
  this.property = prop;
  this.colors = ['red', 'blue', 'green'];
 }url

 // 超類方法
 SuperClass.prototype.get_super_value = function(){
  return this.property;
 }prototype

 // 子類
 function SubClass(prop, sub_prop){
  //繼承超類
  SuperClass.call(this, prop);
  this.sub_property = sub_prop;
 }對象

 // 繼承超類的原型
 extend(SubClass, SuperClass);blog

 //子類方法
 SubClass.prototype.get_sub_value = function(){
  return this.sub_property;
 };繼承

 var instance1 = new SubClass(true, false);
 var instance2 = new SubClass(true, false);token

 instance1.colors.push('black');

 alert(instance1.colors); // red,blue,green,black
 alert(instance2.colors); //red,blue,greenget

 alert(instance1 instanceof SubClass); // true
 alert(instance1 instanceof SuperClass); // true原型

相關文章
相關標籤/搜索