简体   繁体   中英

displayName() inner function is returned from the outer function before being executed

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

What's different (and interesting) is that the displayName() inner function is returned from the outer function before being executed.

How is outer function not getting executed? Outer function is makeFunc() and displayName() is inner function. I can see "Mozilla" being printed. Doesn't that mean that first makeFunc is getting executed and then displayName ?

What's the point that I am missing?

makeFunc is called and it creates the name variable and the displayName function, and returns displayName . When you call makeFunc it creates, but doesn't execute, the inner function. By the time you call myFunc , the name variable from inside makeFunc is gone, but, since displayName referenced it, myFunc is a closure that also holds the value of name from when the closure was created.

When you invoking makeFunc you are creating a scoped function displayName, which has acces to the current value of name. Then makeFunc returns this function. It will not be executed, it is handled similar to objects. You can pass the function around. Or execute it explicitly as you do in your last statement.

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