在新建立的物件中定義 SetterGetter

JavaScript 允許我們在物件文字語法中定義 getter 和 setter。這是一個例子:

var date = {
    year: '2017',
    month: '02',
    day: '27',
    get date() {
        // Get the date in YYYY-MM-DD format
        return `${this.year}-${this.month}-${this.day}`
    },
    set date(dateString) {
        // Set the date from a YYYY-MM-DD formatted string
        var dateRegExp = /(\d{4})-(\d{2})-(\d{2})/;
        
        // Check that the string is correctly formatted
        if (dateRegExp.test(dateString)) {
            var parsedDate = dateRegExp.exec(dateString);
            this.year = parsedDate[1];
            this.month = parsedDate[2];
            this.day = parsedDate[3];
        }
        else {
            throw new Error('Date string must be in YYYY-MM-DD format');
        }
    }
};

訪問 date.date 屬性將返回值 2017-02-27。設定 date.date = '2018-01-02 將呼叫 setter 函式,然後解析字串並設定 date.year = '2018'date.month = '01'date.day = '02'。嘗試傳遞格式不正確的字串(例如 hello)會引發錯誤。