<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>两种类型间的继承</title>
<script type="text/javascript">
//创建公共的父函数
function Flyer(name,speed){
this.name = name;
this.speed = speed;
}
//把他们有关飞行速度的函数写入Fler的原型中:
Flyer.prototype.fly = function(){
console.log(`${this.name}以${this.speed}的速度在飞行!`);
}
//飞机大作战中的东西:
//1.飞机
function Plane(name,speed,score){
// Fler(name,speed);
//上面一行代码存在的问题:它调用父类型构造函数,其中this默认是window
//解决方案:call 只要this不是我想要调用的,可以通过call随便替换 语法:父类型构造函数.call(this,参数一,参数二。。。。。。)
Flyer.call(this,name,speed);
this.score = score;//this -->window
}
//让Plane的原型对象继承Flayer的原型对象
Object.setPrototypeOf(Plane.prototype,Flyer.prototype);
//把击落飞机后的得分函数写在Plane![在这里插入图片描述](https://img-blog.csdnimg.cn/20190807170934839.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4NDA5NzY3,size_16,color_FFFFFF,t_70)的原型中:
Plane.prototype.getScore = function(){
console.log(`击落${this.name}得分是${this.score}`);
}
//2.飞机在飞行过程中捕捉到的可以增加寿命的蜜蜂
function Bee(name,speed,award){
Flyer.call(this,name,speed);
this.award = award;
}
//让Bee的原型对象继承Flayer的原型对象
Object.setPrototypeOf(Bee.prototype,Flyer.prototype);
//把飞机捕获蜜蜂,增加寿命这个函数写入Bee的原型中
Bee.prototype.getAward = function(){
console.log(`击落${this.name}获得${this.award}`);
}
//在飞机和蜜蜂中,有共同的两个属性:名字(name)和速度(speed)
//故而让他们两个都继承自同一个父元素,在调用时,就可以直接在父函数中调用,节省内存
var plane = new Plane("飞机",100,20);
plane.fly();
plane.getScore();
var bee = new Bee("小蜜蜂",80,"一条命");
bee.fly();
bee.getAward();
</script>
</head>
<body>
</body>
</html>
飞机大作战游戏引发的类型之间的继承问题
最新推荐文章于 2020-01-29 10:30:09 发布