繁体   English   中英

为什么JavaScript Closure返回未定义

[英]why is JavaScript Closure returning 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。

privateCounter不是函数,因此不返回任何内容。

increment是一个函数,但是您没有在其后加上() ,因此您没有调用它,它会警告将函数转换为字符串的结果。

如果要调用它( alert(makeMyCounter.increment()); ),则它将返回undefined因为它没有return语句。

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

makeMyCounter.increment()

接下来的事情您不会返回方法,因此它将是不确定的。 添加退货:

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

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

当您运行函数时,只需增加其值,但没有return语句。

在javascript中,如果您的函数没有return语句,则默认情况下将返回undefined

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM