简体   繁体   中英

Javascript: Why do I put “()” after a variable when calling it in console.log?

I'm working through examples in the ebook "eloquent javascript." On page 51, in the Functions chapter, in the Closure section, there's the following example:

function wrapValue2(n) {

  var localVariable = n; 
    return function() {
       return localVariable; 
  };
}

 var wrap2 = wrapValue2(3);
   console.log(wrap2());

As you can see in the last line of the code above, "console.log(wrap2());," the variable is being called inside of console.log. I was having some trouble re-writing this code until I realized there are parenthesis after the variable! Why would I put parenthesis after a variable?

Don't I only do that after a function?

Is this command using the variable as a function? If so, why?

Is it because the object contained within the variable is a function? That doesn't seem very likely.

Thanks in advance!

Exactly: those parentheses are used to call wrap2 , because it's a function.

You use

var wrap2 = wrapValue2(3);

And the function wrapValue2 returns another function.

So wrap2 is a function.

The function ...

function wrapValue2(n) {
  var localVariable = n; 
    return function() {
       return localVariable; 
  };
}

returns a function (see return function() ) ... that will need executed to get the answer.

因为wrap2将在最后作为函数,而wrapValue2返回的function不是value

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