gpt4 book ai didi

javascript - 无法枚举 getter/setter 属性

转载 作者:行者123 更新时间:2023-12-03 19:00:54 25 4
gpt4 key购买 nike

我正在编写一些反射代码以尝试删除属性和函数,但我似乎根本无法获得 getter/setter。

我对属性的反射代码是:

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是可枚举的,它返回为未定义。因此,考虑到它可能以某种方式显示在上面的原型(prototype)中,我尝试提升一个级别,但仍然未定义。

最佳答案

要枚举 getter,请在原型(prototype)上使用 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)));

关于javascript - 无法枚举 getter/setter 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com