简体   繁体   中英

why is JavaScript Closure returning undefined

I know something very basic I am missing . But can't find what's wrong with it ?

<!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>

Why is privateCounter returning undefined ? But when debugged via browser , it is being assigned 1 though .

privateCounter isn't a function, so it doesn't return anything.

increment is a function, but you didn't put () after it, so you aren't calling it and it will alert the result of converting the function to a string.

If you were to call it ( alert(makeMyCounter.increment()); ), then it would return undefined because it has no return statement.

You are using method reference as property, to call method properly use it like that:

makeMyCounter.increment()

next thing You not return in method so it will be undefined. Add return:

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

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

When you run your function you just increment its value but there is no return statement.

In javascript if your function has no return statement undefined will be returned by default.

if you need your new value return privateCounter in increment and decrement functions

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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