基於 ECMAScript 6 即 ECMAScript 2015 的 javascript class 類封裝的簡單使用

來源:互聯網
上載者:User

基於 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


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.