JS面向对象模拟动物继承
<script>
/*Animal构造函数*/
function Animal(name,color,legNum){
this.name=name;
this.color=color;
this.legNum=legNum;
}
/*Animal往原型上添加方法*/
Animal.prototype.eat=function (food) {
console.log(`${this.name}喜欢吃${food}`);
}
/*继承构造函数的方法*/
Cat.prototype=new Animal();
Dog.prototype=new Animal();
/*继承构造函数的参数,继承Animal的属性*/
/*构造Cat函数*/
function Cat(name,color,legNum,hobby) {
/*把Animal的属性都继承过来,现在改变this指向,注意这里的是this指的是Cat对象,arguments指的是name,color,legNum*/
Animal.apply(this,arguments);
/*注意自己新增的新特性要写在参数的最后*/
this.hobby=hobby;
}
function Dog(name,color,legNum,hobby) {
Animal.apply(this,arguments);
this.hobby=hobby;
}
Cat.prototype.yield=function () {
console.log(`${this.color}的${this.name},有${this.legNum}条腿,它的兴趣是:${this.hobby}喜欢对着人喵喵叫!`);
}
Dog.prototype.yield=function () {
console.log(`${this.color}的${this.name},有${this.legNum}条腿,它的兴趣是:${this.hobby}喜欢对着人汪汪叫!`);
}
var cat= new Cat("猫","白色","4","懒洋洋睡觉!");
var dog= new Dog("狗","黄色","4","喜欢看门");
/*白色的猫,有4条腿,喜欢吃鱼,它的兴趣是:懒洋洋睡觉!*/
cat.eat("鱼");
/*黄色的狗,有4条腿,喜欢吃骨头,它的兴趣是:喜欢看门*/
dog.eat("骨头");
dog.yield();
cat.yield();
</script>