Class

阅读阮一峰老师的ES6入门的学习笔记。

Class 基本语法

基本概念

class关键字,可以看做语法糖。大部分功能ES5通过构造函数生成新对象都可以完成。class写法让对象原型的写法更清晰。

1
2
3
4
5
6
7
8
9
10
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
1
2
3
4
5
6
7
8
9
10
11
//定义类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

与ES5构造函数比较

定义

  • class Point等价于function Point

  • constructor是构造方法,等价于ES5中构造函数内定义的内容

  • this与ES5一样,代表实例对象

  • 定义“类”的方法不需要加上function关键字,直接写函数名以及函数体。与ES5在构造函数的 原型对象 上(Point.prototype)上定义方法

  • “类”的方法之间不需要逗号分隔

  • 可以使用Object.assign方法,一次向类添加多个方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Point {
    constructor(){
    // ...
    }
    }
    Object.assign(Point.prototype, {
    toString(){},
    toValue(){}
    });

使用

  • 与ES5构造函数一样,通过new命令创造实例对象

  • 与ES5 不同 类内部定义的方法是不可枚举的 (non-enumerable)

  • 类的构造函数,不使用new无法调用。ES5中构造函数可以不通过new调用

  • ES6 不存在变量提升所以需要先声明父类再使用

  • “类”的属性名,可以采用表达式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    let methodName = "getArea";
    class Square{
    constructor(length) {
    // ...
    }
    [methodName]() {
    // ...
    }
    }

属性

  • 与构造函数相同typeoffunction
  • Point.prototype.constructor也为自身

constructor

  • 类的默认方法,通过new生成对象实例时自动调用。
  • 没有定义时,会默认添加空的constructor方法
  • 默认返回对象实例(this)也可以返回别的对象
  • 类的构造函数,不使用new无法调用。

类的实例对象

  • 与ES5相同,实例的属性除非显示的定义在this上,否则都是定义在原型上class
  • 与ES5相同,类的所有实例共享同一个原型对象

Class表达式

  • 和函数一样可以使用表达式形式定义

    1
    2
    3
    4
    5
    const MyClass = class Me {
    getClassName() {
    return Me.name;
    }
    }
    • 类的名字是MyClass
    • Me只能在Class内部可用
    • Me和函数名一样,可以省略