2015-04-21 146 views
3

我正在處理一些反射代碼以嘗試刪除屬性和函數,但我似乎無法得到getters/setters。無法枚舉getters/setters屬性

反射代碼我對性質是:

Reflector = function() { }; 

Reflector.getProperties = function(obj) { 
    var properties = []; 
    var proto = obj; 
    while (proto != Object.prototype) { 
    console.log('Scrapping proto: ', proto); 
    for (var prop in proto) { 
     console.log('typeof ' + prop + ": ", typeof obj[prop]); 
     if (typeof obj[prop] != 'function') { 
     properties.push(prop); 
     } 
    } 
    proto = Object.getPrototypeOf(proto); 
    } 
    return properties; 
}; 

而且它的一個樣本運行(與我的調試消息)是:

var SimpleTestObject = function() { 
    this.value = "Test1"; 
    this._hiddenVal = "Test2"; 
    this._readOnlyVal = "Test3"; 
    this._rwVal = "Test4"; 
}; 
SimpleTestObject.prototype = { 
    get readOnlyVal() { 
    return this._readOnlyVal; 
    }, 
    get rwVal() { 
    return this._rwVal; 
    }, 
    set rwVal(value) { 
    this._rwVal = value; 
    }, 
    func1: function() { 
    // Test 
    } 
}; 
SimpleTestObject.func2 = function(test) { /* Test */ }; 
SimpleTestObject.outsideVal = "Test5"; 

var props = Reflector.getProperties(SimpleTestObject); 
console.log('props: ', props); 
console.log('Object.getOwnPropertyNames: ', Object.getOwnPropertyNames(SimpleTestObject)); 
console.log('rwVal property descriptor: ', Object.getOwnPropertyDescriptor(SimpleTestObject, 'rwVal')); 
console.log('rwVal (2) property descriptor: ', Object.getOwnPropertyDescriptor(Object.getPrototypeOf(SimpleTestObject), 'rwVal')); 

我希望看到作爲輸出到什麼我Reflection.getProperties(SimpleTestObject)['readOnlyVal', 'rwVal', 'outsideVal'],但是我只看到outsideVal。此外,當我試圖使用getOwnPropertyDescriptor()來查看rwVal是否可枚舉時,它回到未定義狀態。所以,想想看,不知怎的,它已經顯示在上面的原型中,我嘗試了一個級別,仍然沒有定義。

+0

是啊,只注意到它的工作原理是這樣的。任何人有任何解決辦法? – xer0x

回答

0

對於枚舉干將請使用Object.keys或Object.getOwnPropertiesNames原型,而不是構造函數或/和實例:

function readGetters(obj) { 
 
    var result = []; 
 
    Object.keys(obj).forEach((property) => { 
 
     var descriptor = Object.getOwnPropertyDescriptor(obj, property); 
 
     if (typeof descriptor.get === 'function') { 
 
      result.push(property); 
 
     } 
 
    }); 
 
    return result; 
 
} 
 

 

 

 
var SimpleTestObject = function() { 
 
    this.value = "Test1"; 
 
    this._hiddenVal = "Test2"; 
 
    this._readOnlyVal = "Test3"; 
 
    this._rwVal = "Test4"; 
 
}; 
 
SimpleTestObject.prototype = { 
 
    get readOnlyVal() { 
 
     return this._readOnlyVal; 
 
    }, 
 
    get rwVal() { 
 
     return this._rwVal; 
 
    }, 
 
    set rwVal(value) { 
 
     this._rwVal = value; 
 
    }, 
 
    func1: function() { 
 

 
    } 
 
}; 
 
SimpleTestObject.func2 = function(test) { /* Test */ }; 
 
SimpleTestObject.outsideVal = "Test5"; 
 

 

 
// For constructor 
 
console.log(readGetters(SimpleTestObject.prototype)); 
 

 
// For instance 
 
var instance = new SimpleTestObject(); 
 
console.log(readGetters(Object.getPrototypeOf(instance)));