JavaScript 类的高级特性与应用
1. 静态方法
静态方法是通过类名而非实例来调用的方法。例如,下面的代码定义了 Range 类的静态方法 parse :
static parse(s) {
let matches = s.match(/^\((\d+)\.\.\.(\d+)\)$/);
if (!matches) {
throw new TypeError(`Cannot parse Range from "${s}".`)
}
return new Range(parseInt(matches[1]), parseInt(matches[2]));
}
调用方式如下:
let r = Range.parse('(1...10)'); // Returns a new Range object
r.parse('(1...10)'); // TypeError: r.parse is not a function
静态方法也被称为类方法,用于与实例方法进行区分。由于静态方法是在构造函数上调用,而不是在特定实例上调用,因此在静态方法中几乎不会使用 this 关键字。
2. Getter、Setter 和其他方法形式
在类体中,可以像在对象字面量中一样定义 g
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



