javascript - ES6 setter - 保持对象干净//将参数映射到实例对象上

标签 javascript ecmascript-6 setter getter-setter

每当在我的对象上设置值时,我想将它们包装在数组中,但我想保持“全局”对象命名空间干净

问题是我有一个包含 8 个具有相同要求的 Prop 的列表

我不希望对象被大量的 getset 污染,加上 this._left 以避免无限循环当设置由 setter 监控的相同 prop 时......

例如:

class Tree {
    constructor (config) {
        this.left = config.left || [this];
        this.right = config.right || [this];
        this.child = config.child || [this];
        this.parent = config.parent || [this];
        this.somethingElse = config.somethingElse || [this];
        // etc.
    }
}

myObj = new Tree();

myObj.left = 2;

我想确保 myObj.next === [2]

<小时/>

我的尝试(污染太严重):

['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(direction => {
    Object.defineProperty(this, prop, {
        set: (val) => {
            if (!Array.isArray(val)) {
                this['_' + prop] = [val]
            } else {
                this['_' + prop] = val;
            }
        },
        get: (val) => {
            return this['_' + prop];
        }
    });
});

最佳答案

如果没有 setter/getter,就不能有 setter/getter。但是,您不一定需要这些下划线前缀的属性来存储值:

['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(prop => {
    var value = [this];
    Object.defineProperty(this, prop, {
        set(val) {
            if (!Array.isArray(val)) {
                val = [val];
            }
            value = val;
        },
        get(val) {
            return value;
        },
        enumerable: true,
        configurable: true
    });
});

关于javascript - ES6 setter - 保持对象干净//将参数映射到实例对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40143480/

相关文章:

PHP 动态设置对象属性

javascript - Breeze 无法使用在 Breeze 1.4.14 中具有 .expand 子句的查询返回扩展实体

javascript - 为什么我的函数一直从我的输入文本字段读取输入?

javascript - 将对象数组转换为键失败

javascript - 如何使用 Dojo 扩展 es6 类

对象值的Javascript setter

javascript - 如何将日期转换为时间戳?

javascript - Div 选择器未在函数定义中发送调试器

javascript - 在 ES6 中,如何将额外的参数传递给 .then() 调用中的函数?

language-agnostic - Allen Holub 写了 "You should never use get/set functions",他是正确的吗?