class

Class in Javascript

2021/06/19

定義類別

在javascript (ES6 /ES2015以後)裡,可以定義類別 (詳參: JavaScript Classes),跟Java不一樣的是,建構式的名稱跟php一樣都是利用關鍵字constructor,但語法不完全一樣。

class Car {

constructor(brand) {


}

}

在javascript,也可以定義類別變數,利用this來取得類別變數,在java裡可以省略this,但是,在javascript裡,因為變數不用定義,省略this,就會被誤認為是區域變數,在php裡,取用物件的屬性與方法是使用「->」,在javascript是跟java一樣,使用「.」:

class Car {

constructor(brand) {

this.carname = brand;

}

}

產生物件

跟java與php一樣,可以透過類別產生物件,並且直接使用類別變數,跟java不一樣的是類別變數預設是public:

class Car {

constructor(brand) {

this.carname = brand;

}

}

mycar = new Car("Ford");

console.log(mycar.carname);

//output:

//Ford

類別變數

類別變數不可以用var、const或let。

class Car {

constructor(brand) {

let this.carname = brand;//syntax error

}

}

類別方法

跟java、php一樣,可以在class裡定義方法。

class Car {

constructor(brand) {

this.carname = brand;

}

present() {

return 'I have a ' + this.carname;

}

}

要注意,雖然方法在很多方面都跟function很像,但是,在這裡不能加上function,會產生語法錯誤。

class Car {

constructor(brand) {

this.carname = brand;

}

function present() { //syntax error

return 'I have a ' + this.carname;

}

}

試試看:

class Car {

constructor(brand) {

this.carname = brand;

}

present() {

return 'I have a ' + this.carname;

}

}

mycar = new Car("Ford");

console.log(mycar.present());

//output:

//I have a Ford

如果拿掉this,就會得到錯誤訊息,因為沒有this,就會成為方法裡的區域變數:

carname is not defined

基本上所有的類別變數都可以被修改 (如同java的public變數)

class Car {

constructor(brand) {

this.carname = brand;

}

}


mycar = new Car("Ford");

mycar.carname = "Toyota";

console.log(mycar.carname);

//output:

//Toyota

私密變數

在ES2020,加上了#,就把這變數設為private變數,private變數也要先定義。另外,可以定義set method跟get method。這樣就可以透過set method來進行有效值的控制。

class Account {

#balance

constructor(init=0) {

this.#balance = (init >= 0) ? init : 0;

}

get balance(){

return this.#balance;

}


set balance(newBalance){

this.#balance = (newBalance >= 0) ? newBalance: this.#balance;

}


}


myaccount = new Account(100);

console.log(myaccount.balance);

myaccount.balance = -2;

console.log(myaccount.balance);

//output:

//100

//100

繼承

繼承 (跟java很像)

class Car {

constructor(brand) {

this.carname = brand;

}

present() {

return 'I have a ' + this.carname;

}

}


class Model extends Car {

constructor(brand, mod) {

super(brand);

this.model = mod;

}

show() {

return this.present() + ', it is a ' + this.model;

}

}


let mycar = new Model("Ford", "Mustang");

document.getElementById("demo").innerHTML = mycar.show();

import/export

要讓別的檔案可以使用我們寫好的類別要使用export (詳參: 淺談JavaScript ES6的import與import{}及export及export default使用方式 )

export default class PersonList{

}

或者

class PersonList{

}


export default PersonList;

利用import就可以使用前面定義的PersonList類別 (PersonList的檔案名稱為person-list.js)

import PersonList from './person-list';

參考資料