2014-10-17 43 views
0

我想了解为什么当我的函数返回一个对象时,变量索引正在更新(增加和减少)。JSON和范围。使用闭包

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

我想返回2号。当我执行这三行console.log(...) – noOne 2014-10-17 07:11:31

+1

'subtract','add'和'getIndex'应该是函数。如果您想了解它的工作原理,请阅读“关闭”。 – elclanrs 2014-10-17 07:13:45

+0

我明白了。谢谢! – noOne 2014-10-17 07:21:15

回答

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 
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 
0

减,加和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; } 
    } 
}();