首頁  >  文章  >  web前端  >  javascript中的__defineGetter__和__defineSetter__介紹_javascript技巧

javascript中的__defineGetter__和__defineSetter__介紹_javascript技巧

WBOY
WBOY原創
2016-05-16 16:39:421599瀏覽

Getter是一種取得一個屬性的值的方法,Setter是一種設定一個屬性的值的方法。可以為任何預先定義的核心物件或使用者自訂物件定義getter和setter方法,從而為現有的物件添加新的屬性。

有兩種方法定義Getter或Setter方法:

1.在物件初始化時定義
2.在物件定義後透過Object的__defineGetter__、__defineSetter__方法來追加定義

在使用物件初始化過程定義Getter和Setter方法時唯一要做的就是在getter方法前面加上“get”,在setter方法前面加上“set”。

還有一點要注意的是getter方法沒有參數,setter方法必須有一個參數,也就是要設定的屬性的新值。

例如:

複製程式碼 程式碼如下:

   o = { 
        value:9, 
        get b() {return this.value;}, 
        set setter(x) {this.value = x;} 
    } 

在物件定義後為物件新增getter或setter方法要透過兩個特殊的方法__defineGetter__和__defineSetter__。這兩 個函數要求第一個是getter或setter的名稱,以string給出,第二個參數是作為getter或setter的函數。

例如我們為Date物件新增一個year屬性:

複製程式碼 程式碼如下:

Date.prototype.__defineGetter__('year', function() {return this.getFullYear();}); 
    Date.prototype.__defineSetter__('year', function(y) {this.setFullYear(y)}); 
     
    var now = new Date; 
    alert(now.year); 
    now.year = 2006; 
    alert(now);

至於採用哪一種形式主要取決於個人的程式風格,採用第一種形式結構緊湊,更容易理解。但假如你想在對象定義以後再添加Getter或Setter,或者這個對象的原型不是你寫的或是內置對象,那麼只好採用第二種方式了。

下面是一個為Mozilla瀏覽器添加innerText屬性的實作:

複製程式碼 程式碼如下:

 HTMLElement.prototype.__defineGetter__  
    ( 
       "innerText",function() 
       //define a getter method to get the value of innerText,  
       //so you can read it now!  
       { 
          var textRange = this.ownerDocument.createRange(); 
          //Using range to retrieve the content of the object 
          textRange.selectNodeContents(this); 
          //only get the content of the object node 
          return textRange.toString(); 
          // give innerText the value of the node content 
       }
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn