js面向对象继承

/**
 * 一、 构造函数绑定
 */
function Animal(){
    this.species = "动物";
}
function Cat(name,color){
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
}
  var cat1 = new Cat("大毛","黄色");
  alert(cat1.species); // 动物


/**
 * 二、 prototype模式
 */
function Cat1(name,color){
    this.name = name;
    this.color = color;
  }


 function extend3(Child, Parent) {   //继承方法,建议用这个


   Child.prototype = new Parent();  
      Child.prototype.constructor = Child; 
  }
extend3(Cat1,Animal);
    //Cat1.prototype = new Animal();  
  //Cat1.prototype.constructor = Cat1;    //构造函数 
  var acat1 = new Cat1("大毛","黄色");
  alert(acat1.species+'3'); // 动物
alert(acat1.name+'3');


/**
 * 三、 直接继承prototype  注意这种方式值能对直接继承prototype 继承不能获取里面的
 */
function Animal1(){ 
this.w='ok';
}
function Cat2(name,color){
    this.name = name;
    this.color = color;
  }
  Animal1.prototype.species = "动物";
Cat2.prototype = Animal1.prototype;
//Cat2.prototype = new Animal1();
  Cat2.prototype.constructor = Cat2;
  var cat3 = new Cat2("大毛","黄色");
  alert(cat3.species+'s'+ cat3.w); // 动物


/**
 * 四、 利用空对象作为中介
 */
function extend(Child, Parent) {


    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
  }


function Animal5(){
    //this.species = "动物";
}
Animal5.prototype.species = "动物";
function Cat5(name,color){
    
    this.name = name;
    this.color = color;
}
extend(Cat5,Animal5);
  var cat5 = new Cat5("大毛","黄色");
  alert(cat5.species+'5'); // 动物


/**
 * 五、 拷贝继承
 */
function Cat6(name,color){
    
    this.name = name;
    this.color = color;
}
function Animal6(){
this.w='s';
}
  Animal6.prototype.species = "动物";
function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
      c[i] = p[i];
      }
    c.uber = p;
  }
extend2(Cat6, Animal6);
  var cat6 = new Cat6("大毛","黄色");
  alert(cat6.species+'=='+cat6.w); // 动物
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值