为什么JavaScript闭包返回未定义

why is JavaScript Closure returning undefined

本文关键字:未定义 返回 闭包 JavaScript 为什么      更新时间:2023-09-26

我知道我缺少一些非常基本的东西。但找不到它的问题?

<!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返回未定义?但当通过浏览器进行调试时,它被分配了1。

您使用方法引用作为属性,要正确调用方法,请这样使用:

makeMyCounter.increment()

下一件事你没有在方法中返回,所以它将是未定义的。添加退货:

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

privateCounter不是一个函数,因此它不会返回任何内容。

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

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

运行函数时,只需增加其值,但没有返回语句。

在javascript中,如果函数没有返回语句,默认情况下会返回undefined

如果您需要新值,请在incrementdecrement函数中返回privateCounter

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