javascript - 概括类型化的 setter 和 getter 的最佳方法是什么?
问题描述
在这个类中概括 setter 和 getter 的最佳方法是什么:
class A {
constructor() {
this._foo = new Foo();
this._bar = new Bar();
}
get foo() {
return this._foo;
}
set foo(value) {
if (value instanceof Foo)
this._foo = value;
else
this._foo = Object.assign(new Foo(), value);
}
get bar() {
return this._bar;
}
set bar(value) {
if(value instanceof Bar)
this._bar = value;
else
this._bar = Object.assign(new Bar(), value);
}
}
编辑
是的,这个问题可以是基于意见的,并且可以用打字语言来解决。但是对于没有迁移选项的现有项目,如何在 es6 中解决它?
在反序列化保存在数据库中的 json 文档后,我需要这个设置器来定义成员的类型:
{
"foo" :{"x":0,"y":0,"z":0},
"bar" : {"propA": "valueA", "propB": "valueB"}
}
解决方案
理论上你可以使用mixin:
const Typed = (key, type, parent = class {}) => class Typed extends parent {
constructor(...props) {
super(...props);
this[`_${key}`] = new type();
}
get [key]() { return this[`_${key}`]; }
set [key](value) {
this[`_${key}`] = value instanceof type ? value : Object.assign(new type, value);
}
}
const A = Typed("foo", Foo, Typed("bar", Bar, class {
//...
});
但是您可能根本不应该使用 getter / setter,而应该修复尝试使用无效值设置属性的代码。
推荐阅读
- rust - 在 rust-webpack-template 的“reqwest”中找不到“阻塞”
- javascript - Google AdSense 审核不断返回,但没有内容错误(JavaScript 客户端呈现)
- javascript - 将多个json对象转换为对象数组
- html - 使用 HTML5 模式进行验证
- reactjs - react js创建本地数据库的方法
- mysql - MySQL 5.7.25 [innoDB],索引基数突然重置/变回 1
- c# - C# 字符串和数字正则表达式
- angular - Angular 9 与 ui 路由器混合导致尝试在设置 AngularJS 注入器之前获取它。如何调试/修复?
- python - 如何加速 Pandas 循环
- java - 如何使用while循环打印“*”n次?