这个类中的二传手和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 中为没有迁移选项的现有项目解决它?
我需要这个setters在反序列化保存在数据库中的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,而是修复尝试使用无效值设置属性的代码。
如果你想抽象 setters/getter 的创建,你当然可以编写一个函数来做到这一点:
function typedAccessor(obj, name, type, internal) {
Object.defineProperty(obj, name, {
get() {
return this[internal];
},
set(val) {
if (val instanceof type)
this[internal] = val;
else
this[internal] = Object.assign(new type, val);
}
});
}
class A {
constructor() {
this._foo = new Foo();
this._bar = new Bar();
}
}
typedAccessor(A.prototype, "foo", Foo, "_foo");
typedAccessor(A.prototype, "bar", Bar, "_bar");
但是,我建议避免这种模式。
我需要这个setters在反序列化json文档后定义成员的类型
最好使用知道如何处理 JSON 表示的自定义静态方法,而不是执行Object.assign
(并希望所有内容都有适当的 setter(。这使您可以更好地控制序列化/反序列化过程,并使类更简单,样板代码更少。
class A {
constructor(foo, bar) {
this.foo = foo;
this.bar = bar;
}
static fromJSON(val) {
return new this(Foo.fromJSON(val.foo), Bar.fromJSON(val.bar);
}
}