2、利用原型继承和类继承两种方案分别实现:Animal(动物)、Elephant(大象),其中Animal有名字(name)、年龄(age)、类型(type,如大象或老虎)等属性和toString(返回动物的name、age、type等属性构成的字符串)、cry(不知道怎么叫喊,空方法)等方法,Elephant有noseLength(鼻子长度)属性和sprayWater(喷水)、toString、cry等方法。(17分)
时间: 2023-07-10 08:26:31 浏览: 201
使用原型继承实现:
```javascript
// 定义 Animal 原型对象
const Animal = {
init(name, age, type) {
this.name = name;
this.age = age;
this.type = type;
},
toString() {
return `name:${this.name},age:${this.age},type:${this.type}`;
},
cry() {},
};
// 定义 Elephant 原型对象
const Elephant = Object.create(Animal);
Elephant.init = function(name, age, noseLength) {
Animal.init.call(this, name, age, "Elephant");
this.noseLength = noseLength;
};
Elephant.sprayWater = function() {
console.log(`${this.name} is spraying water!`);
};
Elephant.toString = function() {
return `${Animal.toString.call(this)},noseLength:${this.noseLength}`;
};
// 测试代码
const elephant = Object.create(Elephant);
elephant.init("Tom", 5, 2);
console.log(elephant.toString()); // 输出:name:Tom,age:5,type:Elephant,noseLength:2
elephant.sprayWater(); // 输出:Tom is spraying water!
```
使用类继承实现:
```javascript
// 定义 Animal 类
class Animal {
constructor(name, age, type) {
this.name = name;
this.age = age;
this.type = type;
}
toString() {
return `name:${this.name},age:${this.age},type:${this.type}`;
}
cry() {}
}
// 定义 Elephant 类
class Elephant extends Animal {
constructor(name, age, noseLength) {
super(name, age, "Elephant");
this.noseLength = noseLength;
}
sprayWater() {
console.log(`${this.name} is spraying water!`);
}
toString() {
return `${super.toString()},noseLength:${this.noseLength}`;
}
}
// 测试代码
const elephant = new Elephant("Tom", 5, 2);
console.log(elephant.toString()); // 输出:name:Tom,age:5,type:Elephant,noseLength:2
elephant.sprayWater(); // 输出:Tom is spraying water!
```
阅读全文