js继承的几种方法 class
- 格式:docx
- 大小:11.27 KB
- 文档页数:3
js继承的几种方法 class
在JavaScript中,使用`class`关键字可以实现面向对象编程中的继承。以下是通过`class`实现继承的几种常见方法:
1. 基本的`class`继承:
```javascript
class Animal {
constructor(name) {
= name;
}
speak() {
console.log(`${} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${} barks.`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // 输出: Buddy barks.
```
2. 调用`super`关键字:
使用`super`关键字可以在子类的构造函数中调用父类的构造函数,并访问父类的方法。
```javascript
class Animal {
constructor(name) {
= name;
}
speak() {
console.log(`${} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
super.speak();
console.log(`${} barks.`);
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // 输出: Buddy makes a sound. Buddy barks.
```
3. 使用`Object.create`:
使用`Object.create`方法可以实现原型链继承。
```javascript
const Animal = {
init: function(name) {
= name;
return this;
},
speak: function() {
console.log(`${} makes a sound.`);
}
};
const Dog = Object.create(Animal);
Dog.init = function(name, breed) {
Animal.init.call(this, name);
this.breed = breed;
return this;
};
Dog.speak = function() {
Animal.speak.call(this);
console.log(`${} barks.`);
};
const dog = Dog.init('Buddy', 'Golden Retriever');
dog.speak(); // 输出: Buddy makes a sound. Buddy barks.
```
这些是在JavaScript中使用`class`关键字实现继承的几种常见方法。选择合适的方法取决于你的需求和设计偏好。