递归Object.defineProperty()getters

时间:2016-06-01 12:07:31

标签: javascript recursion prototype

我尝试递归地将类构造函数参数中的对象值指定为类的属性。无法弄清楚如何进行递归 - 获得超出的最大调用堆栈大小'和无限循环大部分时间。 这是演示:

const Locale = function(rules) {    
    for (let prop in rules) {
        Object.defineProperty(this, prop, {
            get: function () {
                console.log('getter for "%s" called', prop)
                return rules[prop];
            }
        });
    }
}

const rules = {
    a: {
        b: {
            c: 'value'
        }
    }
}

const locale = new Locale(rules);

console.log(locale.a.b.c);

现在我得到以下控制台输出:

getter for "a" called
value

如何为rules对象的每个级别分配一个getter?预期的控制台输出:

getter for "a" called
getter for "b" called
getter for "c" called
value

2 个答案:

答案 0 :(得分:1)

您需要为Locale对象的每个嵌套级别创建一个rules对象:

const Locale = function(rules) {    
    for (let prop in rules) {
        Object.defineProperty(this, prop, {
            get: function () {
                console.log('getter for "%s" called', prop);

                // create new Locale if object, return value if not an object
                if( rules[prop] !== null && typeof rules[prop] === 'object' )
                    return new Locale( rules[prop] );
                else
                    return rules[prop];
            }
        });
    }
}

const rules = {
    a: {
        b: {
            c: 'value'
        }
    }
}

const locale = new Locale(rules);
console.log(locale.a.b.c);

答案 1 :(得分:0)

如果只想使用函数而不是类,则可以:

app.UseAuthentication();
        app.UseMvc();