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

猜你喜欢

转载自www.cnblogs.com/yaogua/p/9213003.html