js面向对象之继承总结

    前段时间写了js面向对象,如何创建类以及如何使用类来生成对象,今天总结一下js面向对象的继承.

    js中的继承分为两中构造函数继承和非构造函数继承.

    js中的继承例子

     

var animal = function(){
   this.species = '动物';
};


var dog = function(name,color){
   this.name = name;
   this.color = color;
};

var xiaoli = new dog('小西','黑色');
//dog如何继承animal呢?
alert(xiaoli.species);  如何是结果为'动物'呢?

    构造函数继承又有许多的方法,

    1.使用call或apply把父元素的构造函数绑定到子元素上去

   

var dog = function(name,color){
   animal.apply(this,agrments);
   this.name = name;
   this.color = color;
};
var huahua = new dog('huahua','红色');
alert(huahua.species)  //'动物'
     2.prototype模式(原型模式)
dog.prototype = new animal();
dog.prototype.constructor = dog;
//让dog的prototype指向animal

var xiaoyu = new dog('小雨','红色');

alert(xiaoyu.species); //'动物'


原型的构造函数指向dog,是因为当原型指向animal时,其构造函数也指向了animal
dog.prototype.constructor = dog;如果没有这一句
alert(dog.prototype.constructor)  //animal
     3.直接继承prototype
var animal = function(){};
animal.prototype.species = '动物';

dog.prototype = animal.prototype;

dog.prototype.constructor = dog;
var dahua = new dog('大花','花色');

alert(dahua.species); //'动物'


//这样结果

alert(animal.prototype,constructor == dog) //结果为true
     4.空对象继承
var b = function(){};

b.prototype = animal.prototype;

dog.prototype = new b();

dog.prototype.constructor = dog;

alert(animal.prototype.constructor == animal) //结果为true


//写成

var extend = function(parent,child){
    var F = function(){};

    F.prototype = parent.prototype;

    child.prototype = new F();

    child.prototype.constructor = child;

};

//上面为一般类库中继承方法的实现;
     5.拷贝属性

        

var animal = function(){};

animal.prototype.species = '动物';

var extend = function(Parent,Child){
    var p = Parent.prototype;
    
    var c = Child.prototype;

    for(var prop in p)
    {
       c[prop] = p[prop];

    }

};

    

转载于:https://my.oschina.net/KangL/blog/110200

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值