如何在 JS 中动态生成 getter 和 setter?
How do I generate getters and setters dynamically in JS?
我有一个具有某些属性的对象,我想循环遍历并为每个对象生成 getter,有什么想法吗?不使用代理?
const obj = {
_count1: 0,
_count2: 23,
_count3: 1,
};
for (const key in object) {
if (Object.hasOwnProperty.call(object, key)) {
// ?
}
}
}
像这样
const x = {
_count: 0,
get count() {
return this._count;
}
}
是这样的吗?
const obj = {
_count1: 0,
_count2: 23,
_count3: 1,
};
for (const [key, value] of Object.entries(obj))
Object.defineProperty(obj, key.slice(1), {
get () { return obj[key]; },
set (value) { obj[key] = value; }
});
obj.count2 = 34;
console.log(obj.count2)
我有一个具有某些属性的对象,我想循环遍历并为每个对象生成 getter,有什么想法吗?不使用代理?
const obj = {
_count1: 0,
_count2: 23,
_count3: 1,
};
for (const key in object) {
if (Object.hasOwnProperty.call(object, key)) {
// ?
}
}
}
像这样
const x = {
_count: 0,
get count() {
return this._count;
}
}
是这样的吗?
const obj = {
_count1: 0,
_count2: 23,
_count3: 1,
};
for (const [key, value] of Object.entries(obj))
Object.defineProperty(obj, key.slice(1), {
get () { return obj[key]; },
set (value) { obj[key] = value; }
});
obj.count2 = 34;
console.log(obj.count2)