我可以在这里使用Javascript Closures而不是全局变量吗?

rba*_*all 0 javascript closures

目前的设置:

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

可以/我应该使用闭包吗?

oll*_*iej 6

这似乎是一件合理的事情,基于上下文,你可以通过用函数表达式代替你的代码来轻松地做到这一点:

 (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);
         });
     });
 })();
Run Code Online (Sandbox Code Playgroud)