我知道我缺少一些非常基本的东西。但是找不到它有什么问题?
<!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。
最佳答案
您正在使用方法引用作为属性,调用方法正确地使用它:
makeMyCounter.increment()
接下来你不会在方法中返回,所以它将是未定义的。添加返回:
return {
increment : function() {
return privateCounter += 1;
},
decrement : function() {
return privateCounter += -1;
}
}
关于javascript - 为什么 JavaScript Closure 返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555469/