不能停止的腳步
在es6中增加了一個class,簡單明了,比ES5下面強多了 每個類都有會有一個構造函數constructor。如果沒有申明,則會默認分配一個空的。 如果需要調父類的構造函數,需要在constructor第一行調用super,至于為什么,已經有N多文檔說明了。 例如:
class a { constructor(m) { this.m_m = m; } }; class b extends a { constructor(m, m1) { super(m); this.m_m1 = m1; } };
在es6中,使用get和set來標明屬的讀寫函數
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);
在這里就會 打印出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了,又是做了大大的簡化。
只需要在類的成員方法前,加一個static關鍵字就可以了,如果同一個類的靜態函數,可以用this來調用。如下面的astatcfun1調用astatcfun,也可以用類名.的方問,如astatcfun2調用astatcfun,建議還是用this,在使用的時候,靜態方法,不需new出對象來,直接用對象.的方式,如下面的testcall調用a的靜態方法。也可以派生給子類。
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"; //同一個類的靜態函數調用函數,只需要用this.就可以 } kkk() { return "kkk"; } ccc() { return a.aaa() + "ccc" + this.kkk(); //同一個類的非靜態函數調用靜態函數,則需要類名.的方式 }}; let c = new a(); console.log(a.bbb()); console.log(c.ccc());
在ES6的派生通過extends這個關鍵字就可以,如
class b extends a() { };
Copyright @ 冬瓜 Powered by: .Text and ASP.NET Theme by: .NET Monster