DIV CSS 佈局教程網

JavaScript 的 get 與 set 使用示例
編輯:JavaScript基礎知識     

巧妙運用 get 與 set,能直接操作物件屬性實現讀寫,大幅提升編程效率。以下是一個典型示例:

var test = {
    _Name : null,
    _Age : 0,

    // _Name 的讀寫
    set name(name) { this._Name = name; },
    get name() { return this._Name; },

    // _Age 的讀寫
    set age(age) { this._Age = age; },
    get age() { return this._Age; }
}

alert(test.name + " " + test.age); // bull 0

test.name = 'lucy';
test.age = 20;
alert(test.name + " " + test.age); // lucy 20

透過 getter 與 setter,我們可以在內部對應到私有欄位(如 _Name、_Age),外部則像操作普通屬性一樣讀寫,既簡潔又便於在存取時加入驗證或加工邏輯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved