0

当前设置:

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);
    });
});

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

4

2 回答 2

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);
         });
     });
 })();
于 2009-03-04T02:29:24.857 回答
3

根据您的评论,您正在寻找的似乎是:

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());
  });
});

这不使用闭包,它只是将最后分配的 ID 存储在函数对象上。然后,如果他们不将该函数用作设置器,则您将返回该值。如果你想使用闭包来做同样的事情,它看起来很像上面的例子:

(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;
    }
  }
})();

顺便说一句,发现闭包的最简单方法是,如果一个函数中的变量尚未var在当前函数内部声明,但已在它所在的其他函数中。正如你在上面看到的,变量placeId没有在selectPlace函数内部声明,这意味着selectPlace函数是一个使用placeId变量的闭包。

于 2009-03-04T07:15:38.287 回答