首页 > 解决方案 > 概括类型化的 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"}
}

标签: javascriptecmascript-6

解决方案


理论上你可以使用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,而应该修复尝试使用无效值设置属性的代码。


推荐阅读