[Note] JS - OOP: Static Members


Posted by urlun0404 on 2022-12-13

「Member」是屬性(property)和方法(method)的代稱,這篇會以ES6 Class的類別語法為主來解釋靜態屬性和靜態方法。


Static Property & Static Method

一般程式語言物件導向中的靜態屬性和靜態方法是不可被instance使用和呼叫,也不能使用 this 關鍵字,靜態方法中也不能使用非靜態屬性(instance屬性)。

在JavaScript裡,靜態屬性和靜態方法是隸屬constructor,不過比較特別的是,JavaScript的靜態方法內是可以用 this 關鍵字呼叫instance本身的屬性和靜態屬性,也能用 this 呼叫靜態屬性。

ES6 Class語法建立靜態屬性和靜態方法的關鍵字是 static

class User {
    static count;

    constructor(account, password){
        this.account = account;
        this.password = password;
        static();
    }

    static showNumberOfUser(){
        console.log(this.count);
    }

    static counter(){
        this.count++;
    }
}

範例中的constructor內會呼叫 counter 函式,代表每創造一個新的User物件就會用靜態變數 count 計數一次。比較特別的是,JavaScript Class語法內部是可以用 this 呼叫靜態成員,因為此時的 this 代表的是User class。

從這個範例的邏輯來看,count 是無法當作instance屬性來記錄所創造的物件數量,也就是如果用User創造一個物件名為 jack,是無法以jack.count 的方式呼叫 count 屬性,因為count代表"User物件總數",是所有物件共有的屬性,所以要用靜態屬性並用靜態方法呼叫。

這邊再舉一個例子,JavaScript Array也有內建的constructor方法,如 Array.from 可以將一個類似陣列(array)的物件轉換為陣列,也就是在沒有陣列的情況下轉換物件,所以理論上沒辦法用 [0, 1, 2].from( /* array-like object */ ) 的類似語法創造陣列。

另外,如果是用constructor function來建立靜態屬性和靜態方法,可以用下列語法:

User.count = 0;
User.counter = function(){
    User.count++;
}



References
static @MDN
The Complete JavaScript Course 2023: From Zero to Expert!










Related Posts

MTR04_1208

MTR04_1208

做一個影片背景的網頁吧

做一個影片背景的網頁吧

MTR04 W2 D19 第二週作業

MTR04 W2 D19 第二週作業


Comments