Chia Yu Pai

Front-End, HTML5, Javascript, CSS3

Posts match “ js ” tag:

Javascript Getter / Setter

| Comments

Modern browsers' (IE9 up, IE8 only on DOM Object) Javascript Engine supported Getter / Setter for Object

IE6-8 could listen onpropertychange event

我們有兩個常見的方法去實作,例子如下:

Sample A:
透過 __defineSetter____defineGetter__ 預設方法榜定

Dog = function (name) {
    this.name = name || 'Doggy';
  
  // Define setter with __defineSetter__ method.

  this.__defineSetter__("name", function(newVal){
    this.bark('My new name is ' + newVal);
  });
}

Dog.prototype.bark = function (msg){
    msg = msg || "I'm " + this.name;
    alert('Bark! ' + msg);
}

Carl = new Dog();
Carl.name = Carl // Alert: Bark! My new name is Carl

Carl.name // Carl

Sample B:
直接使用 setget 關鍵字定義

Dog = function (name) {
    this._name = name || 'Doggy'; // Default name without alert.

}

Dog.prototype = {
    bark: function (msg) {
    msg = msg || "I'm " + this.name;
        alert('Bark! ' + msg);
  },
  // Define Setter

  set name(newVal) {
    this._name = newVal;
        this.bark('My new name is ' + newVal);
  },
  // Define Getter

  get name() {
    return this._name;
  }
}

Carl = new Dog();
Carl.name = Carl // Alert: Bark! My new name is Carl

Carl.name // Carl

透過 Setter / Getter 的設定可以輕鬆的監聽物件方法的改變,目前最常用到的非屬 two-way binding 的專案。可以直接用十分抽象的方法讓使用者改變 Javascript 中物件的屬性值來換取 DOM 的直接內容變化,達到驚人的易用水準。

Frameworks: