Page 198 - 你不知道的JavaScript(下卷)
P. 198
3.4.4 static
当子类 Bar 从父类 Foo 扩展的时候,我们已经看到 Bar.prototype 是 [[Prototype]] 链接到
Foo.prototype 的。然而,Bar() 也 [[Prototype]] 链接到 Foo()。这一点可能并不显而易见。
但是,在为一个类声明了 static 方法(不只是属性)的情况下这就很有用了,因为这些是
直接添加到这个类的函数对象上的,而不是在这个函数对象的 prototype 对象上。考虑:
class Foo {
static cool() { console.log( "cool" ); }
wow() { console.log( "wow" ); }
}
class Bar extends Foo {
static awesome() {
super.cool();
console.log( "awesome" );
}
neat() {
super.wow();
console.log( "neat" );
}
}
Foo.cool(); // "cool"
Bar.cool(); // "cool"
Bar.awesome(); // "cool"
// "awesome"
var b = new Bar();
b.neat(); // "wow"
// "neat"
b.awesome; // undefined
b.cool; // undefined
小心不要误以为 static 成员在类的原型链上。实际上它们在函数构造器之间的双向 / 并行
链上。
Symbol.species Getter 构造器
static 适用的一个地方就是为派生(子)类设定 Symbol.species getter(规范内称为
@@species)。如果当任何父类方法需要构造一个新实例,但不想使用子类的构造器本身时,
这个功能使得子类可以通知父类应该使用哪个构造器。
举例来说,Array 有很多方法会创造并返回一个新的 Array 实例。如果定义一个 Array 的子
类,但是想要这些方法仍然构造真正的 Array 实例而不是你的子类实例,就可以这样使用:
class MyCoolArray extends Array {
// 强制species为父构造器
static get [Symbol.species]() { return Array; }
代码组织 | 175
图灵社区会员 avilang(1985945885@qq.com) 专享 尊重版权