如何在javascript闭包中传递参数并在没有外部环境帮助的情况下保持其内存?

如何在javascript闭包中传递参数并在没有外部环境帮助的情况下保持其内存?,javascript,ecmascript-6,closures,Javascript,Ecmascript 6,Closures,我有一个场景,比如我将从一个地方调用一个函数,它将在另一个地方发出函数。但是我还需要第一个函数的参数,而不需要在中间传递函数。 所以我想可能有一种方法可以用闭包来实现。所以大家在这个实现中帮助我 var add = (x)=> { var counter = x; return function (c) {counter += c; return counter} }; add(5)(2); add()(2); //Assuming the value

我有一个场景,比如我将从一个地方调用一个函数,它将在另一个地方发出函数。但是我还需要第一个函数的参数,而不需要在中间传递函数。 所以我想可能有一种方法可以用闭包来实现。所以大家在这个实现中帮助我

 var add = (x)=> {
   var counter = x;
     return function (c) {counter += c; return counter}
   };
   add(5)(2);
   add()(2); //Assuming the value of 5 is someway inside the parent's memory

您需要设置一个全局变量

var map
然后,您可以在任何位置使用地图参照:

var map; //global variable to be access anywhere

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });

  //add the listener to the map within the initMap
  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });

}

//this function is calle when the button is clicked which calls the placemarker function outside the init
function addMarker(){
        placeMarker({lat: -34.397, lng: 150.644});
}


//this can now be called from anywhere
function placeMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
}
JSFIDDLE: