Can I use Javascript Closures here instead of a global variable?

こ雲淡風輕ζ 提交于 2019-12-06 15:51:49

问题


Current setup:

var placeId;
function selectPlace(place) {
    $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
    $('#map').hide(400);
    placeId = place.Id;
}

$(document).ready(function()
{
    $('#postMessage').click(function() {
        alert("PlaceId: " + placeId);
    });
});

Can/should I be using closures?


回答1:


Based on your comments, it seems like what you're looking for is this:

function selectPlace(place) {
  if(!place){
    return selectPlace.placeId;
  }else{
    $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
    $('#map').hide(400);
    selectPlace.placeId = place.Id;
  }
}

$(document).ready(function(){
  $('#postMessage').click(function() {
    alert("PlaceId: " + selectPlace());
  });
});

This isn't using a closure, it just stores the last assigned ID on the function object. Then you'd return the value if they don't use the function as a setter. If you wanted to use a closure to do the same thing, it would look a lot like the example above:

(function(){
  var placeId;

  window.selectPlace = function(place) {
    if(!place){
      return placeId;
    }else{
      $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
      $('#map').hide(400);
      placeId = place.Id;
    }
  }
})();

By the way, the easiest way to spot a closure is if a function has variables in it that haven't been declared with var inside of the current function, but have been in some other function it sits inside. As you can see above, the variable placeId isn't declared inside of the selectPlace function, meaning that the selectPlace function is a closure that uses the placeId variable.




回答2:


It seems a reasonable thing to do, based on the context, you can easily do it by substituting your code with a function expression a la:

 (function(){
     var placeId;
     // It looks like you want selectPlace to be a global function?
     // hence i'm using assignment of a function expression here
     selectPlace = function (place) { 
         $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
         $('#map').hide(400);
         placeId = place.Id;
     }

     $(document).ready(function()
     {
         $('#postMessage').click(function() {
             alert("PlaceId: " + placeId);
         });
     });
 })();


来源:https://stackoverflow.com/questions/609023/can-i-use-javascript-closures-here-instead-of-a-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!