
JavaScript 类为面向对象编程 (OOP) 提供了现代化的语法支持,涵盖继承、封装和多态等核心概念。本文将深入探讨 JavaScript 类和继承的创建、使用方法以及高级应用。
ES6 引入了 class 关键字,使类的定义更加清晰简洁。
<code class="javascript">class 类名 {
  构造函数() {
    // 初始化代码
  }
  方法名() {
    // 方法代码
  }
}</code><code class="javascript">class Animal {
  constructor(name, type) {
    this.name = name;
    this.type = type;
  }
  speak() {
    console.log(`${this.name} 发出声音。`);
  }
}
const dog = new Animal('Buddy', '狗');
dog.speak(); // 输出:Buddy 发出声音。</code>继承允许一个类继承另一个类的属性和方法,使用 extends 关键字实现。
<code class="javascript">class 子类 extends 父类 {
  constructor() {
    super(); // 调用父类构造函数
    // 子类额外初始化代码
  }
}</code><code class="javascript">class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} 发出声音。`);
  }
}
class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 调用父类构造函数
    this.breed = breed;
  }
  speak() {
    console.log(`${this.name},一只${this.breed},汪汪叫。`);
  }
}
const dog = new Dog('Buddy', '金毛寻回犬');
dog.speak(); // 输出:Buddy,一只金毛寻回犬,汪汪叫。</code>子类可以重写父类的方法,使用子类版本的实现。
立即学习“Java免费学习笔记(深入)”;
<code class="javascript">class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} 发出声音。`);
  }
}
class Cat extends Animal {
  speak() {
    console.log(`${this.name} 喵喵叫。`);
  }
}
const cat = new Cat('Whiskers');
cat.speak(); // 输出:Whiskers 喵喵叫。</code>super.方法名() 调用父类方法。JavaScript 不直接支持多重继承,但可以使用 Mixin 模式来模拟。
<code class="javascript">const FlyMixin = {
  fly() {
    console.log(`${this.name} 正在飞翔。`);
  }
};
class Bird {
  constructor(name) {
    this.name = name;
  }
}
Object.assign(Bird.prototype, FlyMixin);
const bird = new Bird('麻雀');
bird.fly(); // 输出:麻雀 正在飞翔。</code>Object.assign() 用于将 Mixin 的方法添加到类原型。静态方法和属性属于类本身,而非实例。
<code class="javascript">class MathUtil {
  static add(a, b) {
    return a + b;
  }
}
console.log(MathUtil.add(5, 3)); // 输出:8</code>Getter 和 Setter 用于控制属性的访问和修改。
<code class="javascript">class Person {
  constructor(name) {
    this._name = name;
  }
  get name() {
    return this._name;
  }
  set name(newName) {
    this._name = newName;
  }
}
const person = new Person('Alice');
console.log(person.name); // 输出:Alice
person.name = 'Bob';
console.log(person.name); // 输出:Bob</code>JavaScript 类和继承是构建复杂应用的关键。理解这些概念能编写更清晰、更易维护的代码。 类提供了一种创建对象并管理其行为的现代方法,继承则允许代码复用和扩展。 Mixin 和静态方法等特性进一步增强了 JavaScript 的面向对象编程能力。
作者:Abhay Singh Kathayat (联系方式略)
以上就是理解 JavaScript 中的类和继承的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号