<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>给原型添加方法</title>
</head>
<body>
<script>
function Humans(){
this.foot=2;
}
Humans.prototype.getFoot=function(){
return this.foot;
}
function Man(){
this.head=1;
}
//继承了Humans
Man.prototype=new Humans();
//添加新方法
Man.prototype.getHead=function(){
return this.head;
}
//重写父类型中的方法
Man.prototype.getFoot=function(){
return false;
}
var man1=new Man();
alert(man1.getFoot()); //false
</script>
</body>
</html>
演示了如何给原型添加方法以及如何在子类中重写父类的方法。在这段代码中,定义了两个构造函数 Humans 和 Man,并通过原型链实现了 Man 继承自 Humans。
在这段代码中,Man 类重写了 Humans 类中的 getFoot 方法,使得在创建 Man 实例时调用 getFoot 方法会返回 false 而不是 2。