2016-07-24 225 views
1

我知道一些非常基本的东西我缺少。但是找不到有什么问题呢?为什么JavaScript Closure返回undefined

<!DOCTYPE html> 
<html> 
<body> 

<p>A function can access variables defined inside the function:</p> 

<button type="button" onclick="alert(makeMyCounter.increment)">Click Me!</button> 

<p id="demo"></p> 

<script> 
    var makeMyCounter = function() { 
     var privateCounter = 0; 


     return { 
      increment : function() { 
       privateCounter += 1; 
      }, 
      decrement : function() { 
       privateCounter += -1; 
      } 
     } 
    }(); 


</script> 

</body> 

为什么privateCounter返回undefined?但是,当通过浏览器调试时,它被分配1。

回答

2

您正使用方法参考物业,调用方法正确地使用它就像你的新价值回归privateCounter

makeMyCounter.increment() 

接下来的事情你不会返回方法,所以它会被定义。 Add return:

return { 
     increment : function() { 
      return privateCounter += 1; 

     }, 
     decrement : function() { 
      return privateCounter += -1; 
     } 
    } 
2

privateCounter不是一个函数,所以它不返回任何东西。

increment是一个函数,但你没有把()放在它之后,所以你没有调用它,它会提示将函数转换为字符串的结果。

如果您打电话给它(alert(makeMyCounter.increment());),那么它将返回undefined,因为它没有return语句。

1

当你运行你的函数时,你只是递增它的值,但是没有返回语句。

在JavaScript中如果你的函数没有返回语句undefined将默认返回。

,如果您需要在incrementdecrement功能

return { 
     increment : function() { 
      privateCounter += 1; 
      return privateCounter; 
     }, 
     decrement : function() { 
      privateCounter += -1; 
      return privateCounter; 
     } 
    }