继承发展史
1.传统形式 –>原型链
- 过多继承了没用的东西
2.借用构造函数 –>call/apply
- 不能继承借用构造函数的原型,原型还是自己的
- 每次构造函数都要多走一个函数,造成运行复杂
3.共享原型
- 不能随便改动自己的原型,不能实现自己个性化的原型
示例:
<script type = "text/javascript">
Father.prototype.lastName = "Deng";
function Father(){
}
function Son() {
}
function inherit(Target,Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
Son.prototype.sex = "male"; //此时给Son添加一个属性,这个属性也会添加到Father上
var son = new Son(); //因为此时他俩指向同一个原型,所以我们说不能实现元素的个性化设计
var father = new Father();
</script>
4.圣杯模式
Father.prototype
function F() {}
F.prototype = Father.porotype
Son.prototype = new F(); //这时先继承再生成新的new,又满足了继承,又不会互相干扰
代码示例:
<script type = "text/javascript">
function inherit(Target,Origin){
function F() {
F.prototype = Father.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Target; //构造对象的超类(真正继承自谁)
}
Father.prototype.lastName = "Deng";
function Father(){
}
function Son() {
}
inherit(Son,Father);
var son = new Son();
var father = new Father();
</script>