【发布时间】:2021-09-05 00:40:56
【问题描述】:
我正在尝试编写一个装饰器来设置一个值,如下面的代码所示
function setter(target: any, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
value: 'Hello world',
enumerable: true,
configurable: true,
});
}
class Test {
@setter
public key: string;
}
const instance = new Test();
console.log(instance.key); // Outputs: 'Hello world'
console.log(JSON.stringify(instance)); // Outputs: '{}'
为什么 JSON.stringify 没有返回 { key: 'Hello world' } 而不是 {}?
我已尝试进一步调试问题
function setter(target: any, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
value: `Time -> ${new Date().getTime()}`,
enumerable: true,
configurable: true,
writable: true,
});
}
class Test {
@setter
public key: string;
}
async function main() {
// Create a promise to wait 2 seconds
const wait = new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, 2000);
});
// Create a new instance
const instance1 = new Test();
// Wait
await wait;
// Create a second instance
const instance2 = new Test();
// Log the values of key in each instance
console.log(instance1.key); // Outputs 'Time -> 1624272363288'
console.log(instance2.key); // Outputs 'Time -> 1624272363288'
}
main();
为什么这些值不是唯一的?是否将关键属性添加到类(原型)级别而不是实例?装饰值是否类似于创建静态值?
【问题讨论】:
-
我认为你不能在那种情况下使用
@setter。如果您只记录instance,您将看到创建了一个对象Test,但没有分配任何值 -
第二个代码中
class Test的定义是什么? -
@JaromandaX 同上。我没有改变它
-
您的
@setter正在装饰Test.prototype.key。instance没有自己的key属性,它是继承的,这就是它没有出现在 JSON 中的原因。 -
装饰器执行一次,将属性添加到
Test.prototype
标签: javascript node.js typescript decorator typescript-decorator