码迷,mamicode.com
首页 > 其他好文 > 详细

学些ES6:类

时间:2015-08-30 12:50:50      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

类(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 }}

学些ES6:类

标签:

原文地址:http://www.cnblogs.com/benben77/p/4770578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!