简介
基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
// es5 定义类
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);
// es6 定义类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Point(1, 2);
// es6 的写法完全可以看作构造函数的另一种写法。
// typeof Point // "function"
// Point === Point.prototype.constructor // true
类的数据类型就是函数,类本身就指向构造函数。
构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。
class Point {
constructor() {}
toString() {}
}
// 等同于下面写法,定义在prototype上
Point.prototype = {
constructor() {},
toString() {},
};
// 在类的实例上面调用方法,其实就是调用原型上的方法。
let p = new Point();
p.constructor === Point.prototype.constructor // true
由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。
class Point {}
// 向类添加两个新方法
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});
类的内部所有定义的方法,都是不可枚举的(non-enumerable)
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
// 返回自身所有可枚举的属性组成的数组
Object.keys(Point.prototype)
// []
// 返回自身所有(包括不可枚举)的属性组成的数组
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
es5行为与其不一致,定义在Point.prototype的属性方法是可枚举的。例如Point.prototype.toString = function () {};
中的toString是可枚举的。
constructor 方法
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象,这样new 出来的对象将不再是该类的实例。
class Foo {
constructor() {
return Object.create(null);
}
}
// constructor方法改变了返回值导致一下表达式返回false
new Foo() instanceof Foo
// false
类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。
类的实例
与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。
class Point {
constructor(x) {
this.x = x;
}
toString() {
console.logz('a');
}
}
var point = new Point(1);
var point2 = new Ponint(2);
// 只有x是定义在this上的,toString是定义在原型上的
point.hasOwnProperty('x') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
// 类的所有实例共享一个原型对象
point.__proto__ === point2.__proto__;
// 这也意味着,可以通过实例的__proto__属性为“类”添加方法。
point.__proto__.say = function () { return 'hello' };
point.say() // 'hello'
point2.say() // 'hello'
取值函数(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
inst.prop
// 'getter'
// 存值函数和取值函数是设置在属性的 Descriptor 对象上的
// getOwnPropertyDescriptor 返回某个对象属性某个属性的描述对象
var descriptor = Object.getOwnPropertyDescriptor( MyClass.prototype, "prop");
"get" in descriptor // true
"set" in descriptor // true
Class 表达式
与函数一样,类也可以使用表达式的形式定义。类的属性名,也可以采用表达式。
let fName = 'say';
const MyClass = class Me {
getClassName() {
// 在函数内部可以使用Me,但是在函数外部就必须使用MyClass引用
return Me.name;
}
[fName]() {
return 'hello'
}
};
// 在使用的表达式的时候,在内部没用到时,可省略类名。
const MyClass = class {}
// 也可以写出立即执行的 Class
let person = new class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('张三');
person.sayName(); // "张三
注意点
- 严格模式:类和模块的内部,默认就是严格模式,考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。
- 类不存在变量提升:因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与继承有关,必须保证子类在父类之后定义。
- name属性:由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性。
- Generator 方法:如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数。
- this 的指向:类的方法内部如果含有this,它默认指向类的实例,但是如果暴露方法到外部的时候,this会指向该方法运行时所在的环境(由于class内部是严格模式,所以this执行undefined)
// 有3种方法解决当暴露方法给外部时,this指向的问题
// 1、在构造函数中绑定this
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
}
// 2、使用箭头函数,箭头函数内部的this总是指向定义时所在的对象。
class Obj {
constructor() {
this.getThis = () => this;
}
}
// 3、使用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;
}
// 如果是,将绑定完的函数缓存在cache中
// 使用原函数作为key 将绑定好的函数作为value
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
}
};
const proxy = new Proxy(target, handler);
return proxy;
}
const logger = selfish(new Logger());
// 此时访问logger的方法,就是访问经过logger的新实例调用bind后得到的方法
静态方法
加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static say() {
return 'hello';
}
static bar() {
return this.say();
}
}
Foo.say() // 'hello'
new Foo().say() // TypeError
// 如果静态方法包含this关键字,这个this指的是类,而不是实例。
Foo.bar() // 'hello'
// 父类的静态方法,可以被子类继承。
class Bar extends Foo {
}
Bar.say() // 'hello'
// 静态方法也是可以从super对象上调用的
class Baz extends Foo {
static say() {
return super.say() + ' Baz'
}
}
Baz.say() // 'hello Baz'
实例属性的新写法
实例属性除了定义在constructor()方法里面的this上面,也可以定义在类的最顶层。
class IncreasingCounter {
// 实例属性_count与取值函数value()和increment()方法,处于同一个层级
// 这时,不需要在实例属性前面加上this。
_count = 0;
constructor(x) {
this.x = x; // 定义在this上
}
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
静态属性
静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
现在有一个提案提供了类的静态属性,写法是在实例属性的前面,加上static关键字。这个新写法大大方便了静态属性的表达。
// 老写法:ES6 明确规定,Class 内部只有静态方法,没有静态属性
class Foo {
// ...
}
// 所以只能使用这种方法来添加静态属性
Foo.prop = 1;
// 新写法:提案
class Foo {
static prop = 1;
}
私有方法和私有属性
私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但 ES6 不提供,只能通过变通方法模拟实现。
一种做法是在命名上加以区别。在名字前加下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。
class Widget {
// 公有方法
foo (baz) {
this._bar(baz);
}
// 私有方法
_bar(baz) {
return this.snaf = baz;
}
}
// 希望外部只访问foo ,但实际外部还是能访问到_bar
另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。
class Widget {
foo (baz) {
bar.call(this, baz);
}
}
function bar(baz) {
return this.snaf = baz;
}
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;
}
};
bar和snaf都是Symbol值,一般情况下无法获取到它们,因此达到了私有方法和私有属性的效果。但是也不是绝对不行,Reflect.ownKeys()依然可以拿到它们。
私有属性的提案
目前,有一个提案,为class加了私有属性。方法是在属性名之前,使用#表示。
class IncreasingCounter {
#count = 0;
get value() {
console.log('Getting the current value!');
return this.#count;
}
increment() {
this.#count++;
}
}
// 只能在类的内部使用this.#count
const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错
class Point {
#x;
#a;
#b;
#xValue = 0;
constructor(x = 0) {
this.#x = +x;
}
// 通过x 来映射 #x
// 由于井号#是属性名的一部分,使用时必须带有#一起使用
// 所以#x和x是两个不同的属性。
get x() {
return this.#x;
}
set x(value) {
this.#x = +value;
}
// 私有方法
#sum() {
return #a + #b;
}
// 私有属性也可以设置 getter 和 setter 方法。
get #x() { return #xValue; }
set #x(value) {
this.#xValue = value;
}
}
私有属性不限于从this引用,只要是在类的内部,实例也可以引用私有属性。
class Foo {
#privateValue = 42;
static getPrivateValue(foo) {
return foo.#privateValue;
}
}
Foo.getPrivateValue(new Foo()); // 42
私有属性和私有方法前面,也可以加上static关键字,表示这是一个静态的私有属性或私有方法。
new.target 属性
new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。
如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。
在函数外部,使用new.target会报错。
function Person(name) {
if (new.target !== undefined) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
// 正常使用new 使用调用时,new.target === Person
}
Class 内部调用new.target,返回当前 Class。
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle); // true
this.length = length;
this.width = width;
}
}
// 需要注意的是,子类继承父类时,new.target会返回子类。
class Square extends Rectangle {
constructor(length) {
// 从父类继承length、width属性
super(length, width);
}
}
var obj = new Square(3);
// 这里new Square 上面的console输出 false
利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。
class Shape {
constructor() {
if (new.target === Shape) {
// 不能直接使用new 调用,会报错,除非是子类继承后使用
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
// 继承
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确,new.target === Rectangle
// Shape类不能被实例化,只能用于继承。