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


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

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

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

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

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

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

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

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

 instance1.colors.push('black');

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM