JavaScript Object Accessors (Getters and Setters)

 

在 ECMAScript 5 裡定義了 Getter 和 Setters

 

一、Getter 用法

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "en",
    get lang() {
        return this.language;
    }
};

console.log(person.lang);

 

以下 function 的寫法,可比較其不同

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "en",
    lang: function () {
        return this.language;
    }
};

console.log(person.lang());

你會發現 Getter 寫法只要執行 person.lang,而不需要加上「()」就可以去執行方法了,

這跟我們的直覺不太一樣;再給一個範例來強調我所說的「直覺」不太一樣。

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "en",
    get lang() {
        return this.language;
    },
    get reset() {
        this.firstName = "";
        this.lastname = "";
        this.language = "";
    }
};

console.log(person.lang);
person.reset;
console.log(person.lang);

 

二、Setters 用法

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "NO",
    set lang(value) {
        this.language = value;
    }
};

person.lang = "en";
console.log(person.language);

 

三、Getter 與 Setter 可以同名稱

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "NO",
    get lang() {
        return this.language;
    },
    set lang(value) {
        this.language = value;
    }
};

person.lang = "en"; //call setter
person.lang;        //call getter

 

四、Object.defineProperty()

使用 Object.defineProperty() 方法,可以額外添加 getters 和 setters

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "en",
    get lang() {
        return this.language;
    }
};

Object.defineProperty(person, "reset", {
    get: function () {
        this.firstName = "";
        this.lastname = "";
        this.language = "";
    }
});

console.log(person.lang);
person.reset;
console.log(person.lang);

 

也可以用來添加屬性值或方法

var person = {
    firstName: "John",
    lastName: "Doe",
    language: "EN"
};

Object.defineProperty(person, "language", { value: "NO" });
console.log(person.language);