面向对象的程序设计(十一)继承的深入了解,了解他的作用

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<script>
function inheritPrototype(subType, superType) {
    function F(){};
    F.prototype = superType.prototype;

    var prototype = new F();

    //下面这句很重要,不信可以注释掉,看看36行console.log(Fn2.prototype.constructor)的控制台输出结果有什么区别
    prototype.constructor = subType;//增强对象
    subType.prototype = prototype;//指定对象
}

function Fn1(name) {
    this.name = name;
}

Fn1.prototype.sayName = function() {
    alert(this.name);
};
Fn1.prototype.fnSayName = function() {
    this.sayName();
};

function Fn2(name, age) {
    Fn1.call(this, name);

    this.age = age;
}

inheritPrototype(Fn2, Fn1);
console.log(Fn2.prototype.constructor);//这里的输出结果必须了解

Fn2.prototype.sayAge = function() {
    alert(this.age);
}

var instance1 = new Fn2('Tom', "19");
instance1.sayName();
instance1.fnSayName();

Fn2.prototype.sayName = function() {//重写了Fn2的sayName方法,而且没有破坏原型链上Fn1的sayName方法
    alert("我的名字是:" + this.name);
}

var instance2 = new Fn1('Tom');
instance2.sayName();
instance2.fnSayName();//这里是关键,输出结果是"Tom"

var instance3 = new Fn2('Locy', "19");
instance3.sayName();
instance3.fnSayName();//这里是关键,输出结果是"我的名字是:Locy"

</script>
</head>
<body>
    
</body>
</html>

 

继承能做到不破坏原型链上的方法前提下,重写其中的一些方法,而且并不影响原型链上其他的实例

posted @ 2013-08-14 16:54  金帛  阅读(190)  评论(0编辑  收藏  举报