在新创建的对象中定义 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)会引发错误。