类(class):
class关键词:
let TestClass = class {};
const instance = new TestClass();
{class Inside {}}
typeof Inside // undefined: block scoped
方法与constructor:
class User {
constructor(id) {this.id = id;}
sayHello(){return ‘hello‘+this.id;}
}
const user = new User(42);
class Foo { constructor() { return Object.create(null); } }
getter setter:
class MyAccount {
get balance() { return this.amount; }
set balance(amount) { this.amount = amount; }
}
也可以这样:
const propertyName = ‘balance‘;
class MyAccount {
get [propertyName]() { return this.amount; }
set [propertyName](amount) { this.amount = amount; }
}
static:
const type = ‘test‘ + ‘Type‘;
class IntegrationTest {
static get [type]() { return ‘integration‘; } // static + get/set + 运行时命名
}
继承:
class A {}
class B extends A{}
function 定义的类也可以被继承:
let A = function (){};
class B extends A {}
isPrototypeOf:
class A {}
class B extends A {}
A.isPrototypeOf(B); // true
A.prototype.isPrototypeOf(new B()) // true
A.prototype.isPrototypeOf(B.prototype) // true
还可以:
let A;
class B extends (A = class {}) {}
class B extends (((beNull) => beNull ? null : class {})(true)) {}
super关键字:
普通方法与构造函数中使用super:
class A {iAmSuper() { return this.youAreSuper; }}
class B extends A {constructor() { super(); this.youAreSuper = true; } }
class C extends B {
iAmSuper() {
return super.iAmSuper();
}
}
class A {constructor(startValue=1, addTo=1) { this.counter = startValue + addTo; }}
class B extends A {
constructor(...args) {
super(...args);
this.counter++;
}
}
判断继承:
// not work for exends null, only for babel or ... ?
class A {hasSuper() { return super.constructor !== Object }}
class A {hasSuper() { return !super.constructor }}