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
相关推荐
橙光成长4 小时前
GameScrcpy:不装模拟器,用键鼠手柄和 TypeScript 脚本接管你的安卓手游
android·javascript·typescript·开源·1024程序员节
米米商聊4 小时前
AI 搜群附件,同一份 PDF 占满前三条?按附件 ID 折叠片段
javascript·人工智能
代码小学生&4 小时前
IIS 反向代理配置完整流程
javascript
SEO_juper5 小时前
PHP 站内搜索词分析器:从买家搜的词里,挖出内容缺口
前端·javascript·node.js·json·1024程序员节
徐同保6 小时前
一个 HTML 属性顶替三行 JS:`inert` 的正确用法
前端·javascript·html
map_3d_vis6 小时前
百度地图画圆 Circle 和矩形 Rectangle(JSAPI 4.0)
前端·javascript·gis·地图·百度地图
@atweiwei16 小时前
LangChainRust 0.33.0 发布:让 Agent 应用更容易运行、观察和评测
服务器·前端·javascript
qq_2744751521 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
GuWenyue1 天前
昵称限 20 字,8 个 emoji 却超长:一个「字」在系统里有四种长度
javascript·数据库·后端
画中有画1 天前
自动化脚本中使用RSA
前端·javascript·自动化