1️⃣ class 概述

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过 class 关键字,可以定义类。基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

  1. // ES5 构造函数
  2. function Fun1(x, y) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. Fun1.prototype.method = function () {
  7. console.log('方法');
  8. };
  9. var f1 = new Fun1(1, 2);
  10. // ES6 class类
  11. class Fun2 {
  12. constructor(x, y) {
  13. this.x = x;
  14. this.y = y;
  15. }
  16. method() {
  17. console.log('方法');
  18. }
  19. }
  20. var f2 = new Fun2(1, 2);

1️⃣ class 的静态方法

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

  1. class Fun {
  2. constructor(x, y) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. method_1() {
  7. console.log('方法 - 1');
  8. }
  9. static method_2() {
  10. console.log('静态方法 - 2');
  11. }
  12. }
  13. var f = new Fun(1, 2);
  14. Fun.method_2() // 静态方法 - 2
  15. f.method_2() // Uncaught TypeError: f.method_2 is not a function

1️⃣ class 类继承

Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。
在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,基于父类实例,只有super方法才能调用父类实例。
重写父类的方法在子类中创建同名的方法,来重写父类的方法

  1. class Fun {
  2. // 构造方法
  3. constructor(x, y) {
  4. this.x = x;
  5. this.y = y;
  6. }
  7. // 父类的成员属性
  8. parentMethod() {
  9. console.log('父类 - 方法');
  10. }
  11. }
  12. class Fun1 extends Fun {
  13. // 构造方法
  14. constructor(x, y, z) {
  15. super(x, y);
  16. this.z = z;
  17. }
  18. sonMethod() {
  19. console.log('子类 - 方法');
  20. }
  21. }
  22. const f = new Fun1(1, 2, 3);
  23. console.log(f); // Fun1 {x: 1, y: 2, z: 3}

1️⃣ class 的特点

类名声不会被提升,与 let 和 const 一样,存在暂时性死区
类中的所有代码均在严格模式下执行
类的所有方法都是不可枚举的
类的所有方法都无法被当做构造函数使用
类的构造器必须使用 new 来调用

1️⃣ class 可计算的成员名

  1. let bl = 'variable'
  2. class lei {
  3. constructor() { }
  4. [bl]() { }
  5. }

1️⃣ new.target 属性

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

  1. function Person1(name) {
  2. console.log(new.target == Person1); // false
  3. }
  4. Person1();
  5. function Person2(name) {
  6. console.log(new.target == Person2); // true
  7. }
  8. let p = new Person2();

1️⃣ get 和 set

get方法用于拦截某个属性的读取操作,可以接受三个参数,依次为目标对象、属性名和 proxy 实例本身(严格地说,是操作行为所针对的对象),其中最后一个参数可选。
set方法用来拦截某个属性的赋值操作,可以接受四个参数,依次为目标对象、属性名、属性值和 Proxy 实例本身,其中最后一个参数可选。

  1. class Fun {
  2. constructor(x, y) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. get method() {
  7. console.log('方法被读取');
  8. return 'method - 返回值'
  9. }
  10. set method(value) {
  11. console.log('方法被修改了');
  12. }
  13. }
  14. let f = new Fun();
  15. console.log(f.method);
  16. console.log(f.method = 'A');