2013-02-28 66 views
10

我想使用屬性描述符來定義一個javascript屬性,該屬性描述符具有自定義屬性,換句話說,除了標準的「值」,「可寫」等等以外的屬性...下面例如我已經定義了屬性屬性描述符具有自定義屬性「customAttr」。對Object.defineProperty的調用工作正常,但後來當我嘗試遍歷屬性描述符的屬性時,我的自定義屬性未列出。我正在嘗試做什麼?謝謝javascript屬性描述符支持自定義屬性嗎?

var o = {}; 

Object.defineProperty(o, "newDataProperty", { 
               value: 101, 
               writable: true, 
               enumerable: true, 
               configurable: true, 
               customAttr: 1 
              }); 


var desc2 = Object.getOwnPropertyDescriptor(o, "newDataProperty"); 

// List the descriptor attributes. 
for (var prop in desc2) { 
    console.log(prop + ': ' + desc2[prop]);  
} 
//PROBLEM: "customAttr" is not listed 
+0

出於興趣,你爲什麼要這樣做? – 2013-02-28 14:08:38

+0

hi james ...請參閱我在下面輸入的註釋...在運行時我想循環所有對象的屬性,檢查哪些是用特定屬性「裝飾」的,並基於這些屬性的存在,缺失和價值,然後繼續做「事情」,如財產的驗證......再次感謝您的答案 – user2073948 2013-02-28 14:20:31

回答

7

不,這是不可能的。這是Object.defineProperty做:

...

  3.讓遞減是調用的結果ToPropertyDescriptor屬性作爲參數。

  4.調用以參數名稱遞減,和真正的ö的[[DefineOwnProperty]]內部方法。

  5.返回O

而在短期,ToPropertyDescriptor簡單地忽略任何非 「枚舉」, 「寫」, 「配置」, 「價值」, 「得」 或 「設置」:

  1. 。 ...

  2. desc是創建最初沒有字段的新屬性描述符的結果。

  3. 如果主叫的的[[HasProperty]]內部方法的OBJ以參數 「enumerable」 的結果爲真,則
    • ...

(重複步驟3對於其他有效的描述符屬性)

  10.返回desc

+2

謝謝......真是遺憾......這一定有很好的理由限制我猜...但它關閉了許多事情的大門......我目前從C#代碼生成JS代碼。我有用屬性裝飾的C#屬性...我想把這些屬性帶到JS代碼中......當我第一次查看JS屬性描述符時,我就像「非常好,這正是我需要的」..哦,好吧......仍然愛着JS ...... – user2073948 2013-02-28 14:11:48

1

在這裏復活舊帖子,但我發現這個想法很有趣。您可以提取一個事實,即函數在JavaScript對象,並使用get功能屬性持有人:

function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) { 
    var descriptor = getCustomPropertyDescriptor(obj, propertyName); 

    descriptor.get.$custom[attributeName] = attributeValue; 
} 

function getPropertyAttributes(obj, propertyName) { 
    var descriptor = getCustomPropertyDescriptor(obj, propertyName); 

    return descriptor.get.$custom; 
} 

function getPropertyAttribute(obj, propertyName, attributeName) { 
    return getPropertyAttributes(obj, propertyName)[attributeName]; 
} 

function getCustomPropertyDescriptor(obj, prop) { 
    var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop); 
    if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$custom) { 
    return actualDescriptor; 
    } 

    var value = obj[prop]; 
    var descriptor = { 
    get: function() { 
     return value; 
    }, 
    set: function(newValue) { 
     value = newValue; 
    } 
    } 
    descriptor.get.$custom = {}; 

    Object.defineProperty(obj, prop, descriptor); 
    return Object.getOwnPropertyDescriptor(obj, prop); 
} 

然後:

var obj = { 
    text: 'value', 
    number: 256 
} 

setPropertyAttribute(obj, 'text', 'myAttribute', 'myAttributeValue'); 

var attrValue = getPropertyAttribute(obj, 'text', 'myAttribute'); //'myAttributeValue' 

小提琴here