Javascript JSON和作用域。使用闭包

Javascript JSON和作用域。使用闭包,javascript,json,scope,Javascript,Json,Scope,我试图理解为什么当我的函数返回一个对象时,变量索引会被更新(加减) var init = (function() { var index = 0; return function() { return { subtract: index -= 1, add: index = index + 1, getIndex: index

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

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。这是因为当返回对象时,将执行该返回对象中的所有属性。所以我的问题是如何防止这种情况发生。

我非常怀疑它返回0。它应该返回未定义的:

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

subtract、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; }
    }
}();

我想把2号还给你。当我执行console.log(…)
subtract
add
,和
getIndex
这三行时,应该是函数。如果你想了解它是如何工作的,请阅读关于“闭包”的文章。我现在明白了。谢谢
var init = (function() {
    var index = 0;

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