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

ES6 setter - keep object CLEAN // map params on instance object

本文关键字:对象 映射 实例 参数 setter ES6      更新时间:2023-09-26

我想在数组中包装值,当它们在我的对象上设置时,但我想保持"全局"对象命名空间CLEAN

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

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

例如:

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]


My attempt (too pollution):

['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
    });
});