不能停止的腳步
在es6中增加了一個(gè)class,簡(jiǎn)單明了,比ES5下面強(qiáng)多了 每個(gè)類都有會(huì)有一個(gè)構(gòu)造函數(shù)constructor。如果沒(méi)有申明,則會(huì)默認(rèn)分配一個(gè)空的。 如果需要調(diào)父類的構(gòu)造函數(shù),需要在constructor第一行調(diào)用super,至于為什么,已經(jīng)有N多文檔說(shuō)明了。 例如:
class a { constructor(m) { this.m_m = m; } }; class b extends a { constructor(m, m1) { super(m); this.m_m1 = m1; } };
在es6中,使用get和set來(lái)標(biāo)明屬的讀寫函數(shù)
class a { constructor(m) { this.m_m = m; } get m() { return this.m_m; } set m(v) { this.m_m = v; }};let testa = new a(1999); console.log(testa.m);
在這里就會(huì) 打印出1999
class a { constructor(m) { this.m_m = m; } get m() { return this.m_m; } set m(v) { this.m_m = v; } mult(k) { return this.m_m * k; } add(k) { return this.m_m + k; } sub(k) { return this.m_m / k; }};
在這里可以看到,不需要用function了,又是做了大大的簡(jiǎn)化。
只需要在類的成員方法前,加一個(gè)static關(guān)鍵字就可以了,如果同一個(gè)類的靜態(tài)函數(shù),可以用this來(lái)調(diào)用。如下面的astatcfun1調(diào)用astatcfun,也可以用類名.的方問(wèn),如astatcfun2調(diào)用astatcfun,建議還是用this,在使用的時(shí)候,靜態(tài)方法,不需new出對(duì)象來(lái),直接用對(duì)象.的方式,如下面的testcall調(diào)用a的靜態(tài)方法。也可以派生給子類。
class a { constructor(m) { this.m_m = m; } static astaticfun() { return 100; } static astatcfun1() { return this.astaticfun() + 200; } static astatcfun2() { return a.astaticfun() + 200; } get m() { return this.m_m; } set m(v) { this.m_m = v; } mult(k) { return this.m_m * k; } add(k) { return this.m_m + k; } sub(k) { return this.m_m / k; }}; // function testcall(){ console.log(a.astaticfun()); console.log(a.astatcfun1()); console.log(a.astatcfun2()); }
class a { static aaa() { return "aaa"; } static bbb() { return this.aaa() + "bbb"; //同一個(gè)類的靜態(tài)函數(shù)調(diào)用函數(shù),只需要用this.就可以 } kkk() { return "kkk"; } ccc() { return a.aaa() + "ccc" + this.kkk(); //同一個(gè)類的非靜態(tài)函數(shù)調(diào)用靜態(tài)函數(shù),則需要類名.的方式 }}; let c = new a(); console.log(a.bbb()); console.log(c.ccc());
在ES6的派生通過(guò)extends這個(gè)關(guān)鍵字就可以,如
class b extends a() { };
Copyright @ 冬瓜 Powered by: .Text and ASP.NET Theme by: .NET Monster