根据您的评论,您正在寻找的似乎是:
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
变量的闭包。