分析 class
class Widget {
constructor(width,height) {
this.width = width || 50;
this.height = height || 50;
this.KaTeX parse error: Expected 'EOF', got '}' at position 14: elem = null; }̲ render(where){
if (this.KaTeX parse error: Expected '}', got 'EOF' at end of input: elem) { this.elem.css( {
width: this.width + “px”,
height: this.height + “px”
} ).appendTo( KaTeX parse error: Expected 'EOF', got '}' at position 10: where ); }̲ } } class Butt…elem = KaTeX parse error: Expected 'EOF', got '}' at position 36: … this.label ); }̲ render(where) {
super(
w
h
e
r
e
)
;
t
h
i
s
.
where ); this.
where);this.elem.click( this.onClick.bind( this ) );
}
onClick(evt) {
console.log( “Button '” + this.label + “’ clicked!” );
}
}
1.(基本上,下面会详细介绍)不再引用杂乱的 .prototype 了。
2. Button 声 明 时 直 接“ 继 承 ” 了 Widget, 不 再 需 要 通 过 Object.create(…) 来 替
换 .prototype 对象,也不需要设置 .proto 或者 Object.setPrototypeOf(…)。
3. 可以通过 super(…) 来实现相对多态,这样任何方法都可以引用原型链上层的同名方
法。这可以解决第 4 章提到过的那个问题:构造函数不属于类,所以无法互相引用——
super() 可以完美解决构造函数的问题。
4. class 字面语法不能声明属性(只能声明方法)。看起来这是一种限制,但是它会排除
掉许多不好的情况,如果没有这种限制的话,原型链末端的“实例”可能会意外地获取
其他地方的属性(这些属性隐式被所有“实例”所“共享”)。所以,class 语法实际上
可以帮助你避免犯错。
5. 可以通过 extends 很自然地扩展对象(子)类型,甚至是内置的对象(子)类型,比如
Array 或 RegExp。没有 class …extends 语法时,想实现这一点是非常困难的,基本上
只有框架的作者才能搞清楚这一点。