class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name) { super(name); // calls the Animal constructor with the name parameter } speak() { console.log(`${this.name} barks.`); } } const fido = new Dog('Fido’); fido.speak(); // Output: Fido barks.
时间: 2024-03-29 16:34:54 浏览: 24
这段代码是使用ES6语法定义了两个类,一个是Animal类,一个是Dog类,其中Dog类继承了Animal类。Animal类有一个构造函数,用于初始化实例属性name,还有一个方法speak,用于打印对象的名称和一个固定的字符串。Dog类也有一个构造函数,它调用了父类Animal的构造函数,并且有一个重写的speak方法,用于打印对象的名称和另外一个固定的字符串。最后,通过创建一个Dog类的实例fido,调用它的speak方法,输出"Fido barks."。
相关问题
ES6:class的定义与继承,从ES5转换成ES6
在ES6中,我们可以使用class关键字来定义一个类,同时也可以使用extends关键字来实现继承。下面是一个使用ES6语法定义和继承类的示例代码:
```
// 定义一个父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// 定义一个子类,继承自父类Animal
class Dog extends Animal {
constructor(name) {
super(name); // 调用父类的constructor方法
}
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog('Mitzie');
d.speak(); // 输出 "Mitzie barks."
```
以上代码中,Animal类是一个父类,其构造函数接受一个name参数,并定义了一个speak方法。而Dog类则继承自Animal类,并且覆盖了speak方法,以实现不同的行为。
如果你想把以上代码从ES5转换成ES6,可以使用一些工具,如Babel等,将其转换成ES6语法。例如,以下是使用ES5语法定义和继承类的示例代码:
```
// 定义一个父类
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a noise.');
};
// 定义一个子类,继承自父类Animal
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(this.name + ' barks.');
};
var d = new Dog('Mitzie');
d.speak(); // 输出 "Mitzie barks."
```
以上代码中,Animal类是一个父类,其构造函数接受一个name参数,并通过原型链定义了一个speak方法。而Dog类则继承自Animal类,并使用Object.create()方法来创建一个新的对象,并将其原型设为Animal.prototype,以实现继承。同时,需要手动设置Dog.prototype.constructor属性,以确保其指向正确的构造函数。最后,覆盖原型上的speak方法以实现不同的行为。
js中class继承练习题
好的,我可以帮你练习一下JS中的class继承问题。以下是一个例子,可以帮助你理解如何在JS中使用class继承。
假设我们有一个父类Animal:
```javascript
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
```
现在我们想创建一个子类Dog,它继承了Animal的属性和方法:
```javascript
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
fetch() {
console.log(`${this.name} fetches.`);
}
}
```
在这个例子中,我们使用extends关键字来指定Dog继承自Animal。在Dog的构造函数中,我们通过super关键字来调用Animal的构造函数,以便我们可以访问Animal的属性。我们还定义了一个新的方法fetch()来扩展Dog的功能。
现在我们可以创建一个Dog实例并调用它的方法:
```javascript
const myDog = new Dog('Rex', 3, 'German Shepherd');
myDog.speak(); // Rex barks.
myDog.fetch(); // Rex fetches.
```
这个例子演示了如何在JS中实现class继承。希望这可以帮助你练习class继承问题!