前段时间写了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];
}
};