简体   繁体   English

为什么JavaScript Closure返回未定义

[英]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 ? 为什么privateCounter返回undefined? But when debugged via browser , it is being assigned 1 though . 但是,当通过浏览器调试时,它却被分配为1。

privateCounter isn't a function, so it doesn't return anything. privateCounter不是函数,因此不返回任何内容。

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

If you were to call it ( alert(makeMyCounter.increment()); ), then it would return undefined because it has no return statement. 如果要调用它( alert(makeMyCounter.increment()); ),则它将返回undefined因为它没有return语句。

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. 当您运行函数时,只需增加其值,但没有return语句。

In javascript if your function has no return statement undefined will be returned by default. 在javascript中,如果您的函数没有return语句,则默认情况下将返回undefined

if you need your new value return privateCounter in increment and decrement functions 如果您需要新值,请在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