基於 ECMAScript 6 即 ECMAScript 2015 的 javascript class 類封裝的簡單使用
文章來源 blog.csdn.net/joyous/article/details/79102169
建立一個 js 檔案 test.js
在下面的例子中,我們首先定義一個名為Polygon 的 class,然後繼承它來建立另一個名為 Square 的 class。注意,建構函式中使用的 super() 只能在建構函式中使用,並且必須在使用 this 關鍵字前調用。
再在 Polygon 的 class 中定義兩個函數 fun1 和 fun2,輸出構造傳入的參數。
/** * 建立兩個 js class, 並定義一個 constructor (構造) */class Polygon { // 建構函式 constructor(height, width) { this.name = 'Polygon'; this.height = height; this.width = width; } // fun1 函數 fun1() { console.log('fun1', this.name, this.height, this.width); } // fun2 函數 fun2() { console.log('fun2', this.name, this.height, this.width); }}// 定義 Square class 並擴充 Polygonclass Square extends Polygon { constructor(height, width) { super(height, width); this.name = 'Square'; }}
建立一個 html 分頁檔
<!DOCTYPE><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script src="test.js" type="text/javascript"></script><script type="text/javascript">// 建立對象var polygon1 = new Polygon(10, 15);var polygon2 = new Polygon(20, 30);polygon1.fun1();polygon1.fun2();polygon2.fun1();polygon2.fun2();var square = new Square(35, 36);square.fun1();square.fun2();</script></head><body><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class">參考代碼</a></body><script type="text/javascript"></script></html>
輸出結果
// polygon1.fun1() 輸出fun1 Polygon 10 15// polygon1.fun2() 輸出fun2 Polygon 10 15// polygon2.fun1() 輸出fun1 Polygon 20 30// polygon2.fun2() 輸出fun2 Polygon 20 30// square.fun1() 輸出fun1 Square 35 36// square.fun2() 輸出fun2 Square 35 36
以上測試基於Google Chrome ver63,我們可以看到 javascript 的 class 完全如預期運行,正確顯示了 polygon 的 fun 和 Square 的 fun,這種定義方式和 C++/ Java 的 class 定義方式非常相似,符合類封裝概念,後端程式員可以完全以 class 的思想來使用 javascript,不會再覺得以前的 javascript 文法略顯不適應(從 C++/Java 文法角度看),對於 C++/Java 程式員需要兼顧 javascript 程式的簡直就是福音。文章來源 blog.csdn.net/joyous/article/details/79102169
Q群討論:236201801