用js构造函数cat,继承方法Animal
时间: 2023-05-25 09:01:02 浏览: 97
好的,让我来回答你的问题。
在 JavaScript 中,我们可以使用以下方式来定义构造函数 `Animal` 和 `Cat`,实现继承关系:
```javascript
// 定义一个 Animal 构造函数
function Animal(name) {
this.name = name;
}
// 在 Animal 的原型上定义一个 sayHi 方法
Animal.prototype.sayHi = function() {
console.log(`Hi, I'm ${this.name}`);
};
// 定义一个 Cat 构造函数,继承自 Animal
function Cat(name, color) {
// 调用 Animal 的构造函数,继承属性
Animal.call(this, name);
this.color = color;
}
// 使用 Object.create 方法,将 Cat 的原型链连接到 Animal 的原型链上
Cat.prototype = Object.create(Animal.prototype);
// 重置 Cat.prototype.constructor,使其指向 Cat 自身的构造函数
Cat.prototype.constructor = Cat;
// 在 Cat 的原型上定义一个 catchMouse 方法
Cat.prototype.catchMouse = function() {
console.log(`${this.name} is catching a mouse!`);
};
```
现在,我们可以实例化一个 `Animal` 和一个 `Cat`,并调用它们的方法:
```javascript
const animal = new Animal('Animal');
const cat = new Cat('Tom', 'grey');
animal.sayHi(); // Hi, I'm Animal
cat.sayHi(); // Hi, I'm Tom
cat.catchMouse(); // Tom is catching a mouse!
```
注意,在构造函数 `Cat` 中,我们使用了 `call` 方法调用了 `Animal` 的构造函数,以继承 `Animal` 的属性。在 `Cat.prototype` 中,我们使用了 `Object.create` 方法来将 `Animal.prototype` 所指向的原型链传递到 `Cat.prototype` 上,从而实现了继承关系。最后,我们重置了 `Cat.prototype.constructor`,使其指向 `Cat` 自身的构造函数,以便在调试时查看自身的构造函数。