簡體   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