程序员scholar 程序员scholar
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
npm

(进入注册为作者充电)

  • ES6

    • ECMAScript 6 简介
    • let 和 const 命令
    • 变量的解构赋值
    • 字符串的扩展
    • 字符串的新增方法
    • 正则的扩展
    • 数值的扩展
    • 函数的扩展
    • 数组的扩展
    • 对象的扩展
    • 对象的新增方法
    • Symbol
    • Set 和 Map 数据结构
    • Proxy
    • Reflect
    • Promise 对象
    • Iterator 和 for-of 循环
    • Generator 函数的语法
    • Generator 函数的异步应用
    • async 函数
    • Class 的基本语法
      • 1. 简介
        • 类的由来
        • constructor 方法
        • 类的实例
        • 取值函数(getter)和存值函数(setter)
        • 属性表达式
        • Class 表达式
        • 注意点
      • 2. 静态方法
      • 3. 实例属性的新写法
      • 4. 静态属性
      • 5. 私有方法和私有属性
        • 现有的解决方案
        • 私有属性的提案
      • 6. new.target 属性
    • Class 的继承
    • Module 的语法
    • Module 的加载实现
    • 编程风格
    • 读懂 ECMAScript 规格
    • 异步遍历器
    • ArrayBuffer
    • 最新提案
    • 装饰器
    • 函数式编程
    • Mixin
    • SIMD
    • 参考链接
  • ES6
  • ES6
scholar
2024-07-26
目录

Class 的基本语法

# Class 的基本语法

# 1. 简介

# 类的由来

JavaScript 语言中,生成实例对象的传统方法是通过构造函数。下面是一个例子。

function Point(x, y) {
  // 构造函数,接收两个参数 x 和 y
  this.x = x;
  this.y = y;
}

// 在 Point 的原型上定义一个方法 toString,用于返回点的字符串表示
Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

// 创建一个 Point 实例
var p = new Point(1, 2);
1
2
3
4
5
6
7
8
9
10
11
12
13

上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,很容易让新学习这门语言的程序员感到困惑。

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过 class 关键字,可以定义类。

基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的 class 改写,就是下面这样。

class Point {
  // 构造方法,接收两个参数 x 和 y
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  // 定义 toString 方法,用于返回点的字符串表示
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

上面代码定义了一个“类”,可以看到里面有一个 constructor 方法,这就是构造方法,而 this 关键字则代表实例对象。也就是说,ES5 的构造函数 Point,对应 ES6 的 Point 类的构造方法。

Point 类除了构造方法,还定义了一个 toString 方法。注意,定义“类”的方法的时候,前面不需要加上 function 这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

ES6 的类,完全可以看作构造函数的另一种写法。

class Point {
  // 构造方法,接收两个参数 x 和 y
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  // 定义 toString 方法,用于返回点的字符串表示
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

typeof Point // "function"
Point === Point.prototype.constructor // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码表明,类的数据类型就是函数,类本身就指向构造函数。

使用的时候,也是直接对类使用 new 命令,跟构造函数的用法完全一致。

class Bar {
  // 定义一个方法 doStuff
  doStuff() {
    console.log('stuff');
  }
}

// 创建 Bar 类的实例
var b = new Bar();
b.doStuff() // "stuff"
1
2
3
4
5
6
7
8
9
10

构造函数的 prototype 属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的 prototype 属性上面。

class Point {
  constructor() {
    // 构造方法
  }

  toString() {
    // 定义 toString 方法
  }

  toValue() {
    // 定义 toValue 方法
  }
}

// 等同于

Point.prototype = {
  constructor() {
    // 构造方法
  },
  toString() {
    // 定义 toString 方法
  },
  toValue() {
    // 定义 toValue 方法
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

在类的实例上面调用方法,其实就是调用原型上的方法。

class B {}
let b = new B();

// 实例 b 的构造函数与类 B 的原型的构造函数是同一个
b.constructor === B.prototype.constructor // true
1
2
3
4
5

上面代码中,b 是 B 类的实例,它的 constructor 方法就是 B 类原型的 constructor 方法。

由于类的方法都定义在 prototype 对象上面,所以类的新方法可以添加在 prototype 对象上面。Object.assign 方法可以很方便地一次向类添加多个方法。

class Point {
  constructor(){
    // 构造方法
  }
}

// 使用 Object.assign 向 Point 类的原型添加方法
Object.assign(Point.prototype, {
  toString() {
    // 定义 toString 方法
  },
  toValue() {
    // 定义 toValue 方法
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

prototype 对象的 constructor 属性,直接指向“类”的本身,这与 ES5 的行为是一致的。

Point.prototype.constructor === Point // true
1

另外,类的内部所有定义的方法,都是不可枚举的(non-enumerable)。

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

// 获取 Point 类原型的可枚举属性
Object.keys(Point.prototype)
// []
// 获取 Point 类原型的所有属性,包括不可枚举属性
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

上面代码中,toString 方法是 Point 类内部定义的方法,它是不可枚举的。这一点与 ES5 的行为不一致。

var Point = function (x, y) {
  this.x = x;
  this.y = y;
};

Point.prototype.toString = function() {
  return '(' + this.x + ', ' + this.y + ')';
};

// 获取 Point 类原型的可枚举属性
Object.keys(Point.prototype)
// ["toString"]
// 获取 Point 类原型的所有属性,包括不可枚举属性
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码采用 ES5 的写法,toString 方法就是可枚举的。

# constructor 方法

constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。

class Point {
  // 空的类
}

// 等同于
class Point {
  constructor() {
    // 默认的构造方法
  }
}
1
2
3
4
5
6
7
8
9
10

上面代码中,定义了一个空的类 Point,JavaScript 引擎会自动为它添加一个空的 constructor 方法。

constructor 方法默认返回实例对象(即 this),完全可以指定返回另外一个对象。

class Foo {
  constructor() {
    // 返回一个新创建的对象,覆盖默认的 this
    return Object.create(null);
  }
}

// 实例化 Foo 类
new Foo() instanceof Foo
// false
1
2
3
4
5
6
7
8
9
10

上面代码中,constructor 函数返回一个全新的对象,结果导致实例对象不是 Foo 类的实例。

类必须使用 new 调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用 new 也可以执行。

class Foo {
  constructor() {
    // 构造方法
  }
}

// 不使用 new 调用会报错
Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'
1
2
3
4
5
6
7
8
9

# 类的实例

生成类的实例的写法,与 ES5 完全一样,也是使用 new 命令。前面说过,如果忘记加上 new,像函数那样调用 Class,将会报错。

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

// 不使用 new 调用会报错
var point = Point(2, 3); // 报错

// 使用 new 调用
var point = new Point(2, 3); // 正确
1
2
3
4
5
6
7
8
9
10
11
12

与 ES5 一样,实例的属性除非显式定义在其本身(即定义在 this 对象上),否则都是定义在原型上(即定义在 class 上)。

// 定义类
class Point {
  constructor(x, y) { // constructor 属性定义在原型上
    this.x = x; // x 属性定义在实例上
    this.y = y; // y 属性定义在实例上
  }

  toString() { // toString 方法定义在原型上
    return '(' + this.x + ', ' + this.y + ')';
  }
}

// 创建实例
var point = new Point(2, 3);

point.toString() // (2, 3)

point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

上面代码中,x 和 y 都是实例对象 point 自

身的属性(因为定义在 this 变量上),所以 hasOwnProperty 方法返回 true,而 toString 是原型对象的属性(因为定义在 Point 类上),所以 hasOwnProperty 方法返回 false。这些都与 ES5 的行为保持一致。

与 ES5 一样,类的所有实例共享一个原型对象。

var p1 = new Point(2, 3);
var p2 = new Point(3, 2);

p1.__proto__ === p2.__proto__ // true
1
2
3
4

上面代码中,p1 和 p2 都是 Point 的实例,它们的原型都是 Point.prototype,所以 __proto__ 属性是相等的。

这也意味着,可以通过实例的 __proto__ 属性为“类”添加方法。

__proto__ 并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性。

var p1 = new Point(2, 3);
var p2 = new Point(3, 2);

// 通过实例的 __proto__ 属性为类添加方法
p1.__proto__.printName = function () {
  return 'Oops';
};

p1.printName() // "Oops"
p2.printName() // "Oops"

var p3 = new Point(4, 2);
p3.printName() // "Oops"
1
2
3
4
5
6
7
8
9
10
11
12
13

上面代码在 p1 的原型上添加了一个 printName 方法,由于 p1 的原型就是 p2 的原型,因此 p2 也可以调用这个方法。而且,此后新建的实例 p3 也可以调用这个方法。这意味着,使用实例的 __proto__ 属性改写原型,必须相当谨慎,不推荐使用,因为这会改变“类”的原始定义,影响到所有实例。

# 取值函数(getter)和存值函数(setter)

与 ES5 一样,在“类”的内部可以使用 get 和 set 关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class MyClass {
  constructor() {
    // 构造方法
  }

  // 定义取值函数
  get prop() {
    return 'getter';
  }

  // 定义存值函数
  set prop(value) {
    console.log('setter: ' + value);
  }
}

let inst = new MyClass();

inst.prop = 123; // 调用存值函数
// setter: 123

console.log(inst.prop); // 调用取值函数
// 'getter'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

上面代码中,prop 属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的 Descriptor 对象上的。

class CustomHTMLElement {
  constructor(element) {
    this.element = element; // 构造方法,接收一个 DOM 元素作为参数
  }

  // 定义取值函数,返回元素的 innerHTML
  get html() {
    return this.element.innerHTML;
  }

  // 定义存值函数,设置元素的 innerHTML
  set html(value) {
    this.element.innerHTML = value;
  }
}

// 获取 html 属性的描述对象
var descriptor = Object.getOwnPropertyDescriptor(
  CustomHTMLElement.prototype, "html"
);

"get" in descriptor  // true
"set" in descriptor  // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

上面代码中,存值函数和取值函数是定义在 html 属性的描述对象上面,这与 ES5 完全一致。

# 属性表达式

类的属性名,可以采用表达式。

let methodName = 'getArea';

class Square {
  constructor(length) {
    this.length = length; // 定义类的构造函数,接收一个参数 length
  }

  // 使用表达式作为方法名,定义 getArea 方法
  [methodName]() {
    return this.length * this.length; // 计算正方形的面积
  }
}

const square = new Square(4);
console.log(square.getArea()); // 输出 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码中,Square 类的方法名 getArea 是从表达式得到的。

# Class 表达式

与函数一样,类也可以使用表达式的形式定义。

const MyClass = class Me {
  // 定义一个方法 getClassName
  getClassName() {
    return Me.name;
  }
};
1
2
3
4
5
6

上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是 Me,但是 Me 只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用 MyClass 引用。

let inst = new MyClass();
console.log(inst.getClassName()); // Me
console.log(Me.name); // ReferenceError: Me is not defined
1
2
3

上面代码表示,Me 只在 Class 内部有定义。

如果类的内部没用到的话,可以省略 Me,也就是可以写成下面的形式。

const MyClass = class { /* 类的定义 */ };
1

采用 Class 表达式,可以写出立即执行的 Class。

let person = new class {
  constructor(name) {
    this.name = name; // 构造方法,接收一个参数 name
  }

  // 定义一个方法 sayName
  sayName() {
    console.log(this.name);
  }
}('张三'); // 立即执行的类

person.sayName(); // "张三"
1
2
3
4
5
6
7
8
9
10
11
12

上面代码中,person 是一个立即执行的类的实例。

# 注意点

(1)严格模式

类和模块的内部,默认就是严格模式,所以不需要使用 use strict 指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。

(2)不存在提升

类不存在变量提升(hoist),这一点与 ES5 完全不同。

new Foo(); // ReferenceError
class Foo {}
1
2

上面代码中,Foo 类使用在前,定义在后,这样会报错,因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。

{
  let Foo = class {};
  class Bar extends Foo {
    // Bar 继承 Foo 类
  }
}
1
2
3
4
5
6

上面的代码不会报错,因为 Bar 继承 Foo 的时候,Foo 已经有定义了。但是,如果存在 class 的提升,上面代码就会报错,因为 class 会被提升到代码头部,而 let 命令是不提升的,所以导致 Bar 继承 Foo 的时候,Foo 还没有定义。

(3)name 属性

由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被 Class 继承,包括 name 属性。

class Point {}
console.log(Point.name); // "Point"
1
2

name 属性总是返回紧跟在 class 关键字后面的类名。

(4)Generator 方法

如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数。

class Foo {
  constructor(...args) {
    this.args = args; // 构造方法,接收多个参数
  }

  // 使用 Generator 方法,定义 Symbol.iterator 方法
  * [Symbol.iterator]() {
    for (let arg of this.args) {
      yield arg; // 依次返回每个参数
    }
  }
}

// 使用 for...of 循环遍历 Foo 类的实例
for (let x of new Foo('hello', 'world')) {
  console.log(x);
}
// hello
// world
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

上面代码中,Foo 类的 Symbol.iterator 方法前有一个星号,表示该方法是一个 Generator 函数。Symbol.iterator 方法返回一个 Foo 类的默认遍历器,for...of 循环会自动调用这个遍历器。

(5)this 的指向

类的方法内部如果含有 this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`); // 调用 print 方法
  }

  print(text) {
    console.log(text); // 打印文本
  }
}

const logger = new Logger();
const { printName } = logger; // 解构赋值,将

 printName 方法从实例中提取出来
printName(); // TypeError: Cannot read property 'print' of undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码中,printName 方法中的 this,默认指向 Logger 类的实例。但是,如果将这个方法提取出来单独使用,this 会指向该方法运行时所在的环境(由于 class 内部是严格模式,所以 this 实际指向的是 undefined),从而导致找不到 print 方法而报错。

一个比较简单的解决方法是,在构造方法中绑定 this,这样就不会找不到 print 方法了。

class Logger {
  constructor() {
    this.printName = this.printName.bind(this); // 在构造方法中绑定 this
  }

  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // "Hello there"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

另一种解决方法是使用箭头函数。

class Obj {
  constructor() {
    this.getThis = () => this; // 使用箭头函数
  }
}

const myObj = new Obj();
console.log(myObj.getThis() === myObj); // true
1
2
3
4
5
6
7
8

箭头函数内部的 this 总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以 this 会总是指向实例对象。

还有一种解决方法是使用 Proxy,获取方法的时候,自动绑定 this。

function selfish(target) {
  const cache = new WeakMap();
  const handler = {
    get(target, key) {
      const value = Reflect.get(target, key);
      if (typeof value !== 'function') {
        return value; // 如果不是函数,直接返回
      }
      if (!cache.has(value)) {
        cache.set(value, value.bind(target)); // 绑定 this
      }
      return cache.get(value); // 返回绑定后的函数
    }
  };
  const proxy = new Proxy(target, handler); // 创建 Proxy
  return proxy; // 返回 Proxy 对象
}

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = selfish(new Logger()); // 使用 Proxy
const { printName } = logger;
printName(); // "Hello there"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

上面代码通过 Proxy 实现了方法的自动绑定,不用每次都手动绑定 this。

# 2. 静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上 static 关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
  // 定义静态方法
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello' - 直接通过类调用静态方法

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function - 静态方法不能通过实例调用
1
2
3
4
5
6
7
8
9
10
11
12

上面代码中,Foo 类的 classMethod 方法前有 static 关键字,表明该方法是一个静态方法,可以直接在 Foo 类上调用(Foo.classMethod()),而不是在 Foo 类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

注意,如果静态方法包含 this 关键字,这个 this 指的是类,而不是实例。

class Foo {
  static bar() {
    this.baz(); // 这里的 `this` 指的是类 Foo
  }
  static baz() {
    console.log('hello');
  }
  baz() {
    console.log('world');
  }
}

Foo.bar() // hello - 静态方法 `bar` 调用了静态方法 `baz`
1
2
3
4
5
6
7
8
9
10
11
12
13

上面代码中,静态方法 bar 调用了 this.baz,这里的 this 指的是 Foo 类,而不是 Foo 的实例,等同于调用 Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

父类的静态方法,可以被子类继承。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  // 子类继承父类的静态方法
}

Bar.classMethod() // 'hello' - 子类可以调用父类的静态方法
1
2
3
4
5
6
7
8
9
10
11

上面代码中,父类 Foo 有一个静态方法,子类 Bar 可以调用这个方法。

静态方法也是可以从 super 对象上调用的。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too'; // 调用父类的静态方法
  }
}

Bar.classMethod() // "hello, too" - 子类的静态方法调用了父类的静态方法
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3. 实例属性的新写法

实例属性除了定义在 constructor() 方法里面的 this 上面,也可以定义在类的最顶层。

class IncreasingCounter {
  constructor() {
    this._count = 0; // 在构造函数中定义实例属性
  }
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

上面代码中,实例属性 this._count 定义在 constructor() 方法里面。另一种写法是,这个属性也可以定义在类的最顶层,其他都不变。

class IncreasingCounter {
  _count = 0; // 在类的顶层定义实例属性
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}
1
2
3
4
5
6
7
8
9
10

上面代码中,实例属性 _count 与取值函数 value() 和 increment() 方法,处于同一个层级。这时,不需要在实例属性前面加上 this。

这种新写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。

class Foo {
  bar = 'hello'; // 实例属性
  baz = 'world'; // 实例属性

  constructor() {
    // 构造函数
  }
}
1
2
3
4
5
6
7
8

上面的代码,一眼就能看出,Foo 类有两个实例属性,一目了然。另外,写起来也比较简洁。

# 4. 静态属性

静态属性指的是 Class 本身的属性,即 Class.propName,而不是定义在实例对象(this)上的属性。

class Foo {
  // 这里定义的是类的内容(实例方法、实例属性)
}

// 静态属性定义在类的外部
Foo.prop = 1;

console.log(Foo.prop); // 1 - 通过类名直接访问静态属性
1
2
3
4
5
6
7
8

上面的写法为 Foo 类定义了一个静态属性 prop。

目前,只有这种写法可行,因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。现在有一个提案 (opens new window)提供了类的静态属性,写法是在实例属性的前面,加上 static 关键字。

class MyClass {
  // 使用 static 关键字定义静态属性
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // 42 - 通过类名访问静态属性
  }
}

// 创建类的实例
const instance = new MyClass();
1
2
3
4
5
6
7
8
9
10
11

这个新写法大大方便了静态属性的表达。

// 老写法
class Foo {
  // 这里定义的是类的内容(实例方法、实例属性)
}

// 在类外部定义静态属性
Foo.prop = 1;

console.log(Foo.prop); // 1

// 新写法
class Foo {
  // 直接在类的内部使用 static 关键字定义静态属性
  static prop = 1;
}

console.log(Foo.prop); // 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

上面代码中,老写法的静态属性定义在类的外部。整个类生成以后,再生成静态属性。这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码组织原则。另外,新写法是显式声明(declarative),而不是赋值处理,语义更好。

# 5. 私有方法和私有属性

# 现有的解决方案

私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但 ES6 不提供,只能通过变通方法模拟实现。

一种做法是在命名上加以区别。

class Widget {

  // 公有方法
  foo (baz) {
    this._bar(baz);
  }

  // 私有方法
  _bar(baz) {
    return this.snaf = baz;
  }

  // ...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

上面代码中,_bar 方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。

另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。

class Widget {
  foo (baz) {
    bar.call(this, baz);
  }

  // ...
}

// 私有方法
function bar(baz) {
  return this.snaf = baz;
}
1
2
3
4
5
6
7
8
9
10
11
12

上面代码中,foo 是公开方法,内部调用了 bar.call(this, baz)。这使得 bar 实际上成为了当前模块的私有方法。

还有一种方法是利用 Symbol 值的唯一性,将私有方法的名字命名为一个 Symbol 值。

const bar = Symbol('bar');
const snaf = Symbol('snaf');

export default class myClass {

  // 公有方法
  foo(baz) {
    this[bar](baz);
  }

  // 私有方法
  [bar](baz) {
    return this[snaf] = baz;
  }

  // ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

上面代码中,bar 和 snaf 都是 Symbol 值,一般情况下无法获取到它们,因此达到了私有方法和私有属性的效果。但是也不是绝对不行,Reflect.ownKeys() 依然可以拿到它们。

const inst = new myClass();

Reflect.ownKeys(myClass.prototype)
// [ 'constructor', 'foo', Symbol(bar) ]
1
2
3
4

上面代码中,Symbol 值的属性名依然可以从类的外部拿到。

# 私有属性的提案

目前,有一个提案 (opens new window),为 class 加了私有属性。方法是在属性名之前,使用 # 表示。

class IncreasingCounter {
  #count = 0; // 私有属性
  get value() { // 公有方法
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() { // 公有方法
    this.#count++;
  }
}
1
2
3
4
5
6
7
8
9
10

上面代码中,#count 就是私有属性,只能在类的内部使用(this.#count)。如果在类的外部使用,就会报错。

const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错
1
2
3

上面代码在类的外部,读取私有属性,就会报错。

下面是另一个例子。

class Point {
  #x; // 私有属性

  constructor(x = 0) {
    this.#x = +x;
  }

  get x() { // 公有方法
    return this.#x;
  }

  set x(value) { // 公有方法
    this.#x = +value;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码中,#x 就是私有属性,在 Point 类之外是读取不到这个属性的。由于井号 # 是属性名的一部分,使用时必须带有 # 一起使用,所以 #x 和 x 是两个不同的属性。

之所以要引入一个新的前缀 # 表示私有属性,而没有采用 private 关键字,是因为 JavaScript 是一门动态语言,没有类型声明,使用独立的符号似乎是唯一的比较方便可靠的方法,能够准确地区分一种属性是否为私有属性。另外,Ruby 语言使用 @ 表示私有属性,ES6 没有用这个符号而使用 #,是因为 @ 已经被留给了 Decorator。

这种写法不仅可以写私有属性,还可以用来写私有方法。

class Foo {
  #a; // 私有属性
  #b; // 私有属性
  constructor(a, b) {
    this.#a = a;
    this.#b = b;
  }
  #sum() { // 私有方法
    return this.#a + this.#b;
  }
  printSum() { // 公有方法
    console.log(this.#sum());
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

上面代码中,#sum() 就是一个私有方法。

另外,私有属性也可以设置 getter 和 setter 方法。

class Counter {
  #xValue = 0; // 私有属性

  constructor() {
    // ...
  }

  get #x() { return this.#xValue; } // 私有 getter 方法
  set #x(value) { // 私有 setter 方法
    this.#xValue = value;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

上面代码中,#x 是一个私有属性,它的读写都通过 get #x() 和 set #x() 来完成。

私有属性不限于从 this 引用,只要是在类的内部,实例也可以引用私有属性。

class Foo {
  #privateValue = 42; // 私有属性
  static getPrivateValue(foo) { // 静态方法
    return foo.#privateValue;
  }
}

Foo.getPrivateValue(new Foo()); // 42
1
2
3
4
5
6
7
8

上面代码允许从实例 foo 上面引用私有属性。

私有属性和私有方法前面,也可以加上 static 关键字,表示这是一个静态的私有属性或私有方法。

class FakeMath {
  static PI = 22 / 7; // 静态属性
  static #totallyRandomNumber = 4; // 静态私有属性

  static #computeRandomNumber() { // 静态私有方法
    return FakeMath.#totallyRandomNumber;
  }

  static random() { // 静态方法
    console.log('I heard you like random numbers…');
    return FakeMath.#computeRandomNumber();
  }
}

console.log(FakeMath.PI); // 3.142857142857143
console.log(FakeMath.random());
// I heard you like random numbers…
// 4
console.log(FakeMath.#totallyRandomNumber); // 报错
console.log(FakeMath.#computeRandomNumber()); // 报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

上面代码中,#totallyRandomNumber 是私有属性,#computeRandomNumber() 是私有方法,只能在 FakeMath 这个类的内部调用,外部调用就会报错。

# 6. new.target 属性

new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

function Person(name) {
  if (new.target !== undefined) { // 判断是否通过 new 调用
    this.name = name; // 如果是,通过 new 调用,设置实例属性 name
  } else {
    throw new Error('必须使用 new 命令生成实例'); // 如果不是,抛出错误
  }
}

// 另一种写法
function Person(name) {
  if (new.target === Person) { // 判断 new.target 是否指向 Person 构造函数
    this.name = name; // 如果是,设置实例属性 name
  } else {
    throw new Error('必须使用 new 命令生成实例'); // 如果不是,抛出错误
  }
}

var person = new Person('张三'); // 正确,通过 new 调用
var notAPerson = Person.call(person, '张三');  // 报错,没有通过 new 调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

上面代码确保构造函数只能通过new命令调用。

Class 内部调用new.target,返回当前 Class。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle); // 判断 new.target 是否是 Rectangle 类
    this.length = length; // 设置实例属性 length
    this.width = width; // 设置实例属性 width
  }
}

var obj = new Rectangle(3, 4); // 输出 true
1
2
3
4
5
6
7
8
9

需要注意的是,子类继承父类时,new.target会返回子类。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle); // 判断 new.target 是否是 Rectangle 类
    this.length = length; // 设置实例属性 length
    this.width = width; // 设置实例属性 width
  }
}

class Square extends Rectangle {
  constructor(length) {
    super(length, width); // 调用父类的构造函数
  }
}

var obj = new Square(3); // 输出 false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面代码中,new.target会返回子类。

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Shape {
  constructor() {
    if (new.target === Shape) { // 判断 new.target 是否是 Shape 类
      throw new Error('本类不能实例化'); // 如果是,抛出错误
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    super(); // 调用父类的构造函数
    this.length = length; // 设置实例属性 length
    this.width = width; // 设置实例属性 width
  }
}

var x = new Shape();  // 报错,Shape 不能被实例化
var y = new Rectangle(3, 4);  // 正确,Rectangle 可以被实例化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

上面代码中,Shape类不能被实例化,只能用于继承。

注意,在函数外部,使用new.target会报错。

编辑此页 (opens new window)
上次更新: 2024/12/28, 18:32:08
async 函数
Class 的继承

← async 函数 Class 的继承→

Theme by Vdoing | Copyright © 2019-2025 程序员scholar
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式