ES6 中的 class 是什么?和ES5构造函数差别是什么?

文章目录

  • [ES6 中的 class 是什么?和ES5构造函数差别是什么?](#ES6 中的 class 是什么?和ES5构造函数差别是什么?)
    • [1.ES6 class](#1.ES6 class)
    • [2.ES6 class 和 ES5 函数构造函数函数 (constructor function) 的差別](#2.ES6 class 和 ES5 函数构造函数函数 (constructor function) 的差別)
    • [3.class 的常见方法](#3.class 的常见方法)
      • [3.1 继承](#3.1 继承)
      • [3.2 static静态方法](#3.2 static静态方法)
      • [3.3 Private fields](#3.3 Private fields)

ES6 中的 class 是什么?和ES5构造函数差别是什么?

1.ES6 class

ES6 class 的心智模型与 C++ / Java 等传统class-based 语言是一致的class-based 语言是一致的

JavaScript 在 ECMAScript 6 (ES6) 之前并没有 class 的语法,而是会通过函数构造函数创建对象,再通过 new 关键字实例。

在 ES6 时引入了 class 的概念,JavaScript class 使用的语法 class 类似于其他 OOP 语言中的 class,但 JavaScript 的 class 是一种语法糖,本质上和其他程序语言 class 的实践方式不一样,JavaScript 的 class 是通过原型继承来模拟 class 的行为。如下面示例:

class 方法:

javascript 复制代码
class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  drive() {
    console.log(`Driving a ${this.brand} ${this.model}`);
  }
}

const myCar = new Car("Tesla", "Model 3");
myCar.drive(); // Driving a Tesla Model 3

class 方法之前:

javascript 复制代码
function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}

Car.prototype.drive = function () {
  console.log(`Driving a ${this.brand} ${this.model}`);
};

const myCar = new Car("Tesla", "Model 3");
myCar.drive(); // Driving a Tesla Model 3

|------------------------------------------------------------------------------------------------------------------|
| ES6 之前,我们会通过函数实现相同功能,而在 ES6 版本中的实现方法,Car class 中的 drive 方法并不是在 class 内部里封装的方法,背后其实是赋值到了 Car 的原型 (prototype) 上而已。 |

2.ES6 class 和 ES5 函数构造函数函数 (constructor function) 的差別

ES6 class 和 ES5 的构造函数 (constructor function) 主要有数个差別:

1.提升 hosting :不同于函数声明的构造函数存在提升,但使用 class 声明则是无法再声明前就使用。

javascript 复制代码
var newClass = new MyClass(); // Uncaught ReferenceError: MyClass is not defined is not defined

class MyClass {}

2.new:class 构造函数必须通过 new 调用,否则会抛出错误。而ES5 的构造函数:不用 new 就只是当普通函数执行。

javascript 复制代码
class Animal {}
const a = Animal(); // Uncaught TypeError: Class constructor Animal cannot be invoked without 'new'

3.class 的常见方法

3.1 继承

ES6 的 class 继承是通过使用 extends 关键字实现的。

假设有一个父 class Animal

javascript 复制代码
class Animal {
  constructor(name) {
    this.name = name;
  }

  eat() {
    console.log(`${this.name} eat food.`);
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

创建一个子 class Dog,继承 Animal class

javascript 复制代码
class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

在这个例子中,Dogclass 继承了Animalclass 的所有属性和方法,也可以重写speak方法。接着,使用Dogclass 创建对象:

javascript 复制代码
const dog = new Dog("HAHA");
dog.eat(); // HAHA eat food.
dog.speak(); // HAHA barks.

3.2 static静态方法

静态方法不能被对象实例继承,只能通过class 本身调用。这意味着,你不能通过对象调用class 方法,而只能通过class 名本身调用。

如果尝试通过对象实例访问静态方法,将抛出一个错误,因为静态方法不能被继承,只能通过class 本身访问。

javascript 复制代码
class MathHelper {
  static add(a, b) {
    return a + b;
  }
}

const math = new MathHelper();
// 当试图通过对象实例访问静态方法,将抛出一个错误
console.log(math.add(2, 3)); // Uncaught TypeError: math.add is not a function

// 只能通过 class 本身访问
console.log(MathHelper.add(2, 3)); // 5

3.3 Private fields

可以通过使用前缀#来实现class 的私有领域(Private fields),包括建立私有的属性或是方法,而私有领域只能在class 内部使用,外部无法存取。

如以下程式码,#privateField为私有变数,只能在Example class 中使用,当实例example 尝试直接获取privateField变数时,会报SyntaxError的错误。

javascript 复制代码
class Example {
  #privateField = 100;

  getPrivateField() {
    return this.#privateField;
  }
}

const example = new Example();
console.log(example.getPrivateField()); // 100
console.log(example.#privateField); // SyntaxError: Private field '#privateField' must be declared in an enclosing class
相关推荐
yqcoder10 小时前
JavaScript 柯里化:把“大餐”拆成“小炒”的艺术
开发语言·javascript·ecmascript
每天吃饭的羊10 小时前
JSZip的使用
开发语言·javascript
前端老石人11 小时前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html
不可能的是12 小时前
从 /simplify 指令深挖 Claude Code 多 Agent 协同机制
javascript
Rkgua12 小时前
事件流模型是什么和DOM事件模型等关系
javascript
W.A委员会12 小时前
多行溢出在末尾添加省略号
开发语言·javascript·css
拉里呱唧13 小时前
一个像在使用PPT的在线 HTML 编辑器:HeyHTML
javascript·交互·html5
changshuaihua00114 小时前
扣子开发指南
javascript·人工智能
光影少年14 小时前
对typescript开发框架的理解?
前端·javascript·typescript
a11177614 小时前
“像风之翼“无人机巡检平台仪表盘
前端·javascript·开源·html·无人机