
JavaScript 类为面向对象编程 (OOP) 提供了现代化的语法支持,涵盖继承、封装和多态等核心概念。本文将深入探讨 JavaScript 类和继承的创建、使用方法以及高级应用。
ES6 引入了 class 关键字,使类的定义更加清晰简洁。
class 类名 {
构造函数() {
// 初始化代码
}
方法名() {
// 方法代码
}
}class Animal {
constructor(name, type) {
this.name = name;
this.type = type;
}
speak() {
console.log(`${this.name} 发出声音。`);
}
}
const dog = new Animal('Buddy', '狗');
dog.speak(); // 输出:Buddy 发出声音。继承允许一个类继承另一个类的属性和方法,使用 extends 关键字实现。
class 子类 extends 父类 {
constructor() {
super(); // 调用父类构造函数
// 子类额外初始化代码
}
}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,一只金毛寻回犬,汪汪叫。子类可以重写父类的方法,使用子类版本的实现。
立即学习“Java免费学习笔记(深入)”;
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 喵喵叫。super.方法名() 调用父类方法。JavaScript 不直接支持多重继承,但可以使用 Mixin 模式来模拟。
BIZOSS-B2C是脱胎于贞龙B2B大型平台的网上商城系统、网上商店系统、网上购物系统的企业级B2C电子商务解决方案。系统设置:这里包含了网店的常用功能和全局配置的开关。包括 商店设置 、支付方式和配送方式 、邮件服务器设置、地区列表、友情链接、自定义导航栏、站点地图。商品管理:网店展示商品的核心。其中包括了 商品分类、商品类型、商品品牌、商品回收站、商品上下架等一些设置。促销管理:这个是我们网
0
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(); // 输出:麻雀 正在飞翔。Object.assign() 用于将 Mixin 的方法添加到类原型。静态方法和属性属于类本身,而非实例。
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(5, 3)); // 输出:8Getter 和 Setter 用于控制属性的访问和修改。
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); // 输出:BobJavaScript 类和继承是构建复杂应用的关键。理解这些概念能编写更清晰、更易维护的代码。 类提供了一种创建对象并管理其行为的现代方法,继承则允许代码复用和扩展。 Mixin 和静态方法等特性进一步增强了 JavaScript 的面向对象编程能力。
作者:Abhay Singh Kathayat (联系方式略)
以上就是理解 JavaScript 中的类和继承的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号