一、构造函数绑定
使用call或apply方法,将父对象的构造函数绑定在子对象上。
function Animal(){
this.species = "动物";
}
function Cat(name,color){
Animal.apply(this,arguments);
this.name=name;
this.color=color;
}
var cat = new Cat('小白','白');
console.log(cat.species);
二、prototype模式
如果猫的prototype对象,指向一个Animal的实例,那么所有猫的实例,就能继承Animal
function Animal(){
this.species = "动物";
}
function Cat(name,color){
this.name=name;
this.color=color;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat('小白','白');
console.log(cat.species);
将Cat的prototype的对象指向一个Animal实例,它相当于安全删除了prototype原来的值,给它赋予了一个新值。
Cat.prototype = new Animal();
任何一个prototype对象都有一个constructor属性,指向它的构造函数,如果没有Cat.prototype = new Animal(),Cat.prototype.constructor是指向Cat的,加上这一行,Cat.prototype.constructor指向Animal。这回导致继承紊乱,必须手动矫正,将Cat的prototype对象的constructor的值改为Cat
Cat.prototype.constructor = Cat
三、直接继承prototype
function Animal(){}
Animal.prototype.species = '动物';
function Cat(name,color){
this.name=name;
this.color=color;
}
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
console.log('cat',Cat.prototype.constructor);
console.log('animal',Animal.prototype.constructor);
与前一种做法相比,这种的优点是效率比较高(不用创建Animal实例),缺点是Animal.prototype和Cat.prototype指向了同一个对象,任何对Cat.prototype的修改都会影响到Animal.prototype。
Cat.prototype.constructor = Cat;
实际上把Animal的prototype对象的constructor属性也改掉了
console.log('cat',Cat.prototype.constructor); //Cat
console.log('animal',Animal.prototype.constructor); //Cat
四、利用空对象作为中介
function Animal(){}
Animal.prototype.species = '动物'
function Cat(name,color){
this.name=name;
this.color=color;
}
var F = function(){}
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
var cat = new Cat('小白','白');
console.log(cat.species);
console.log(Animal.prototype.constructor); // Animal
F是空对象,所以几乎不占内存,修改Cat的prototype对象就不会影响到Animal的prototype对象
可以将上述方法封装成一个函数
function extend(child,parent){
var F = function(){};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = Cat;
}
使用方法:
extend(Cat,Animal);
var cat = new Cat('小白','白');
console.log(cat.species);
五、拷贝继承
首先把Animal上所有不变的属性都放到prototype对象上,
function Animal(){}
Animal.prototype.species = '动物';
function Cat(name,color){
this.name=name;
this.color=color;
}
再写一个函数实现拷贝的目的
function extend(child,parent){
var p = parent.prototype;
var c = child.prototype;
for(var i in p){
c[i] = p[i];
console.log(c[i]);
}
}
使用方法:
extend(Cat,Animal);
var cat = new Cat('小白','白');
console.log(cat.species);