欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于__defineGetter__ 和__defineSetter__的說明

 更新時(shí)間:2007年05月12日 00:00:00   作者:  
作者:anbutu
來源:http://anbutu.javaeye.com/blog/post/194276
關(guān)鍵字: JavaScript   Mozilla __defineGetter__ __defineSetter__

Getter是一種獲取一個(gè)屬性的值的方法,Setter是一種設(shè)置一個(gè)屬性的值的方法??梢詾槿魏晤A(yù)定義的核心對(duì)象或用戶自定義對(duì)象定義getter和setter方法,從而為現(xiàn)有的對(duì)象添加新的屬性。
有兩種方法來定義Getter或Setter方法:

在對(duì)象初始化時(shí)定義 
在對(duì)象定義后通過Object的__defineGetter__、__defineSetter__方法來追加定義 
在使用對(duì)象初始化過程來定義Getter和Setter方法時(shí)唯一要做的事情就是在getter方法前面加上“get”,在setter方法前面加上“set”。
還有一點(diǎn)要注意的就是getter方法沒有參數(shù),setter方法必須有一個(gè)參數(shù),也就是要設(shè)置的屬性的新值。
例如:

復(fù)制代碼 代碼如下:

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

在對(duì)象定義后給對(duì)象添加getter或setter方法要通過兩個(gè)特殊的方法__defineGetter__和__defineSetter__。這兩個(gè)函數(shù)要求第一個(gè)是getter或setter的名稱,以string給出,第二個(gè)參數(shù)是作為getter或setter的函數(shù)。
例如我們給Date對(duì)象添加一個(gè)year屬性:

復(fù)制代碼 代碼如下:

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);    

至于采用哪種形式主要取決于個(gè)人的編程風(fēng)格,采用第一種形式結(jié)構(gòu)緊湊,更容易理解。但是假如你想在對(duì)象定義以后再添加Getter或Setter,或者這個(gè)對(duì)象的原型不是你寫的或是內(nèi)置對(duì)象,那么只好采用第二種方式了。
下面是一個(gè)為Mozilla瀏覽器添加innerText屬性的實(shí)現(xiàn):

復(fù)制代碼 代碼如下:

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    
   }    
); 

相關(guān)文章

最新評(píng)論