<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>call和apply实现的继承</title>
</head>
<body>
<p>
由构造函数和call()或者apply()方法实现的javascript继承
</p>
</body>
<script>
//Animal的构造函数
function Animal(name,age){
this.name = name;
this.age = age;
this.showInfo = function(){
alert("它的名字:"+this.name+",它"+this.age+"岁了");
}
}
//call的用法
function Cat(name,age,sex){
Animal.call(this,name,age); //call(this,参数列表)
this.sex = sex;
this.showSex = function(){
alert("它是一只"+this.sex+"猫");
}
}
//apply的用法
function Dog(name,age,cry){
Animal.apply(this,arguments); //apply(this,arguments)
this.cry = cry;
this.showCry = function(){
alert("他的叫喊声:"+this.cry);
}
}
var cat = new Cat("咪咪",2,"母");
cat.showInfo();
cat.showSex();
 
var dog = new Dog("震天吼",4,"汪汪。。。");
dog.showInfo();
dog.showCry();
</script>
</html>
posted on 2016-10-12 10:45  子了  阅读(443)  评论(0编辑  收藏  举报