[英]Is there a way to generate getter and setter pairs in typescript class?
[英]Is there a way to dynamically add getter to a class in javascript/typescript?
我需要一些有关 JavaScript 功能的指导或专业知识。 我正在研究 TypeScript ATM,特别是装饰器功能。
有没有办法将 getter 方法动态添加到原型 object 中,以便代替实例上的普通属性访问执行它。
以下是一些代码示例:
class Car {
@decorate
color: string = 'red';
drive(): {
return 'Driving';
}
}
function decorate(target, key): void {
//would be cool to add a getter and update
//the prototype in target to contain such getter
//I know this won't work, but to get the idea.
target[key] = get function() {
console.log(`Accessing property: ${key}`);
return eval(`this.${key}`)
}
}
然后,当我创建 object 并尝试访问.color
const car = new Car();
car.color;
理想情况下我会在控制台看到
Accessing property: color
您可以在 JavaScript 中使用Proxy
。 正如 MDN 所述,它允许您创建一个 object 来代替原始 object,但它可能会重新定义基本的 Object 操作,例如获取、设置和定义属性。 代理对象通常用于记录属性访问、验证、格式化或清理输入等。
class Car {
color = 'red'
drive() {
return 'Driving'
}
}
const proxy = new Proxy(new Car(), {
get(target, key) {
console.log(`Accessing property: ${key}`);
return Reflect.get(target, key)
}
})
proxy.color // prints "Accessing property: color" and returns value of color.
在普通的 javascript 中,您可以使用Object.defineProperty将 getter 和 setter 动态添加到 object。
这是我最初的评论。
如果您只想装饰 object 的某些字段,那么 MDN 示例将是最简单的正确方法:
const o = {a: 0};
Object.defineProperty(o, 'b', { get() { return this.a + 1; } });
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.