variables - difference between closure and function in javascript - JavaScript闭包是如何工作的?

js new function用法 / javascript / function / scope / closures

对于那些对闭包的概念(例如函数、变量等)有一定了解,但对闭包本身并不了解的人,你将如何解释JavaScript闭包?

28 revs, 21 users 17%



Answer #1
var plane = function(defaultAirport) {

  var lastAirportLeft = defaultAirport;

  var car = {
    driver: {
      startAccessPlaneInfo: function() {
        setInterval(function() {
          console.log("Last airport was " + lastAirportLeft);
        }, 2000);
      }
    }
  };
  car.driver.startAccessPlaneInfo();

  return {
    leaveTheAirport: function(airPortName) {
      lastAirportLeft = airPortName;
    }
  }
}("Boryspil International Airport");

plane.leaveTheAirport("John F. Kennedy");