2012-01-26 76 views
2

它可以創建在JavaScript getter和setter設定器如圖生成通用getter和上javascript對象

Object.defineProperty 
__define***__ 

在所有這些情況下,屬性的名稱是已知的。

是否有可能創建一個通用的。

通過這個我的意思是,我有一個getter和或setter,它被稱爲不考慮屬性名稱。

這可能嗎? 如果是這樣,怎麼樣?

關於。

注: 我在發佈問題後發現了這些問題。看起來目前不可能,因爲第一個答案表明。

Is it possible to implement dynamic getters/setters in JavaScript?

Monitor All JavaScript Object Properties (magic getters and setters)

回答

7

有當非現有屬性作爲函數調用時執行的非標準功能__noSuchMethod__()

但我不認爲你確實在尋找JavaScript(尚)。

+0

感謝。這是我也意識到的。看起來我必須以舊函數的方式來執行它,直到它被實現。 – ritcoder 2012-01-27 08:46:59

1

此時不能在標準javascript中使用。

0

我想你預計此處理自己:

if (!object.hasOwnProperty('foo')) { 
    // object has a foo property, its value might be undefined 

} else if (typeof object.foo != 'undefined') { 
    // there is a foo property elsewhere on object's prototye chain with 
    // a value other than undefined 

} else { 
    // the foo property might exist on the prototype chain with 
    // a value of undefined, or might not exist on the chain at all 
} 
+2

我不是真的在追隨。如果我調用obj.foo並且foo未定義,那麼將如何調用代碼?我的意思是一個完整的工作示例將不勝感激。 – ritcoder 2012-01-27 08:15:18

+0

我的意思是說其他人說「你不能這樣做」,所以我只是補充說,你應該在調用之前檢查obj.foo是否存在。以上是如何做到這一點的工作代碼,但它不會告訴你'foo'是否可以調用。有一個關於如何確定什麼是可調用上的[是功能]討論(http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/13b14565817a35ba/b9e22a812194a9f3?hl=en&lnk=gst&q =爲+上comp.lang.javascript可調用#b9e22a812194a9f3)線程。 – RobG 2012-01-30 00:13:05

+0

好的。我想要做的是真正陷阱缺少的屬性的電話和舉報。這是我正在進行的一個項目的一部分。因此,我實際上並不知道將會調用哪些屬性。 – ritcoder 2012-02-17 14:28:19

0

我覺得你們都喜歡這個

function getterSetter() 
{ 
var valA; 
this.set=function (propName,val) 
{ 
if(typeof this[propName] =='function') 
{ 
return false; 
} 
this[propName]=val; 
} 
this.get=function (propName,val) 
{ 
if(typeof this[propName] =='function') 
{ 
return false; 
} 
return this[propName]; 
} 
} 

這裏集合尋找的東西和獲得方法是setter和getter。你可以用下面的代碼來驗證它。

var testObj=new getterSetter(); 
testObj.set('valA',10); 
alert(testObj.get('valA')); 

此外,檢查propName設置/獲取不是一個函數。

+0

的想法是要能夠知道什麼時候一個不存在的屬性或方法做出請求,並執行一些自定義的功能 - 就像動態的方式在C#中工作。 – ritcoder 2012-10-16 01:40:48