JSON和范围。使用闭包

时间:2014-10-17 07:10:35

标签: javascript json scope

我试图理解为什么当我的函数返回一个对象时,变量索引被更新(添加和减去)。

var init = (function() {
    var index = 0;
    return function() {

            return {

                    subtract: index -= 1,
                    add: index = index + 1,
                    getIndex: index

            }

    }
})();

console.log(init().getIndex);  // 1
console.log(init().add); // 2
console.log(init().getIndex);  //2

而是返回0。这是因为当返回对象时,返回该对象中的所有属性都是执行的。所以我的问题是如何防止这种情况发生。

3 个答案:

答案 0 :(得分:0)

我非常怀疑它会返回0.它应该返回undefined:

var f = init();

// f is now the returned function. Therefore:

f.getIndex; // should be undefined
f().getIndex; // should be 1

因此,要获得预期的输出,请将代码更改为:

console.log(init()().getIndex);  // 1
console.log(init()().add); // 2
console.log(init()().getIndex);  //2

答案 1 :(得分:0)

var init = (function() {
    var index = 0;
    return function() {
        return {
            subtract: function() { return --index; },
            add:      function() { return ++index; },
            getIndex: function() { return index; }
        }
    }
})();

console.log(init().getIndex());  // 0
console.log(init().add()); // 1
console.log(init().getIndex());  // 1

答案 2 :(得分:0)

减法,add和getIndex不作为函数启动。它们正在接收值-1,0和0。

返回操作集

var init = (function() {
    var index = 0;

    return {
        subtract: function () { index -= 1 },
        add: function () { index + 1 }, // Should probably be += here
        getIndex: function () { return index; }
    }
}();