zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SQL大圣之路笔记——SQL 字段中英文字母如何区分大小写
    Python(二十五)
    Python(二十四)
    Python(二十二)
    Python(二十一)
    Python(二十)
    Python(十九)
    Python(十八)
    python(十七)
    python(十六)
  • 原文地址:https://www.cnblogs.com/yaogua/p/9213003.html
Copyright © 2011-2022 走看看