继承方式一:类式继承
在学习继承前,首先要理解继承的原则:A1的prototype中的值是可改变的,并且A1的改动会影响到A2;A2的prototype是可改变的,A2的改动不能影响到A1
在记住此大前提下开始学习继承的类式继承方式
1.类式继承最原始也是最简单的继承方式
function animal(){};
animal.prototype = {};
function cat(){};
cat.prototype = new animal();
2.类式继承用的最多的继承方式—组合式继承
function animal(){
this.color = ["red"]
};
animal.prototype = {};
function cat(){}
cat.prototype = new animal();
var cat1 = new cat();
var cat2 = new cat();
cat1.color.push("white");
//输出 ["red","white"]
说明:cat的原型指向animal的实例,此时animal的实例属性变成cat的原型属性,cat1修改了属性时修改的是cat的原型属性,cat的原型属性是被实例cat1和实例cat2共享的,因此无论cat1还是cat2修改了原型属性,因此实例的属性都是cat的原型属性
改进:
function animal(){
this.color = ["red"]
};
animal.prototype = {};
function cat(){
animal.call(this);
}
cat.prototype = new animal();
var cat1 = new cat();
var cat2 = new cat();
cat1.color.push("white");
//输出["red"]
说明:1.animal.call(this);加入cat构造函数中由于this指执行时的函数即cat,使得this.color = ["red"]成为实例属性,由于cat1,cat2是实例因此具有属性_proto_指向cat.prototype,而cat.prototype是animal的实例,因此prototype中存有属性_proto_指向animal.prototype
2.animal.call(this)覆盖了new cat()中的值即构造函数中的属性覆盖了原型中的属性,因此使得cat1 cat2具有不同的属性成为可能
不足:animal在这样一个过程中使用两次,第一次是cat.prototype = new animal();第二次是animal.call(this);有没有改进方法呢?
3.寄生组合继承
为解决以上现两次使用animal的情况,那就减少一次animal的使用吧!call调用是为了使得属性成为私有属性,减少它就不能达到我们的目的了,显然不能减,那就只能减少new animal()了
目标cat.prototype = animal.prototype,由于_proto_隐藏的,因此可以使用cat._proto= temp._proto_,temp._proto_ = temp.prototype,temp.prototype = animal.prototype就能减少一次animal的使用
写成方法:
function extend(cat,animal){
function temp(){};
temp.prototype = animal.prototype;
cat.prototype = new temp();
cat.prototype.constructor = cat;//重建
cat.super = animal.prototype;//新建,必要时查看super方法,查看animal原型
}
function animal(name){
this.name = name;
}
animal.prototype.sayname = function(){};
function cat(){
animal.call(this);
}
extend(cat,animal);//区别: 原来是cat.prototype = new animal();
cat.prototype.age = 1;

浙公网安备 33010602011771号