简体   繁体   English

从函数调用返回对象的函数会打印未定义

[英]Invoking function of a returned object from function prints undefined

var unique = function(){

var n=0;
return function(){

    return {

        inc : function(){
            n++;
            console.log(n);
        }

    };

 };
};

console.log(unique()().inc());

The code above prints 1 and then undefined what is the reason undefined gets printed ? 上面的代码先打印1,然后再打印undefined,打印undefined的原因是什么?

Because you asked to log the value returned by inc , and it doesn't return anything. 因为您要求记录inc返回的值,但它不返回任何内容。

If you don't want to print anything, 如果您不想打印任何东西,

console.log(unique()().inc());

should be 应该

unique()().inc();

If you expect the new value of n to be printed, 如果您希望打印出新的n值,

inc : function(){ n++; console.log(n); }

should be 应该

inc : function(){ n++; console.log(n); return n; }

you have 2 console.log, one inside inc (that prints 1), the other in the last line, (that prints undefined). 您有2 console.log,一个在inc内部(显示1),另一个在最后一行(显示未定义)。

You can add return n; 您可以添加return n; after the first console inside inc inc的第一个console之后

    inc : function(){
        n++;
        console.log(n);
        return n;
    }

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

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