首頁  >  文章  >  web前端  >  JavaScript中class是什麼?怎麼使用?

JavaScript中class是什麼?怎麼使用?

不言
不言原創
2018-12-24 11:18:569506瀏覽

class是關鍵字,用來處理ECMAScript 2015所採用的JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?類,ECMAScript 2015(ekma腳本)是JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?的標準規格。由國際組織標準化,在Google Chrome和Internet Explorer 11及更高版本等現代瀏覽器中廣泛採用。

JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?

使用class我們可以簡單地在JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?中編寫物件導向的程式設計。

我們下面來看class的使用方法

基本的程式如下。在class關鍵字之後,設定在中括號中的變數和方法。

class { 
  设置变量和方法
  }

我們來看具體的範例

程式碼如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <title>JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?</title>
  </head>
  <body>
    <script>
      class Person {
        constructor(name) {
          this.name = name;
        }
        say() {
          console.log("你好," + this.name + "课程!");
        }
      }
      var x = new Person("玉女心经");
      x.say();
      var y = new Person("独孤九剑")
      y.say();
    </script>
  </body>
</html>

運行結果如下

JavaScript中class是什麼?怎麼使用?中class是什麼?怎麼使用?

##我們來分析上述程式碼

class Person {
  constructor(name) {
    this.name = name;
  }
  say() {
    console.log("你好," + this.name + "课程!");
  }
}

使用class關鍵字定義「Person」類別。

在括號中,我們定義了一個名為「constructor」的方法和一個名為「say」的方法。

var x = new Person("玉女心经");
x.say();
var y = new Person("独孤九剑")
y.say();

建立實例需要使用「new」關鍵字。這樣做,就會呼叫類別的“constructor”方法。

透過在new類別完成時指定不同的名稱,分別透過say方法輸出「玉女心經」和「獨孤九劍」的字串。

這篇文章到這裡就全部結束了,更多精彩內容大家可以關注php中文網的相關欄位來進一步的學習! ! !

以上是JavaScript中class是什麼?怎麼使用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn