Skip to content

继承

一句话解释

继承是 mechanism 哪里新 类 derives 属性 and 方法从 existing 类.

用大白话说

Inheritance lets you create a new class that automatically gets all the properties and methods of an existing class. The new class (child/subclass) can then add its own features or override inherited ones.

例如, if you have a Vehicle class with 速度 and 停止(), you can create a Car class that inherits from Vehicle and adds numberOfDoors. The Car automatically has 速度 and 停止() from Vehicle, plus its own numberOfDoors.

Inheritance promotes code reuse — you write shared behavior once in the parent and all children inherit it. However, deep inheritance hierarchies can be hard to maintain. Modern code often prefers composition (building objects from smaller pieces) over deep inheritance.

示例

javascript
class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound.`; }
}

class Dog extends Animal {
  speak() { return `${this.name} barks.`; }
}

const dog = new Dog("Rex");
console.log(dog.speak()); // "Rex barks."

Dog inherits 从 Animal. 它 overrides speak() 方法到 provide dog-特定 behavior 虽然 keeping name 属性从 Animal.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表