Как вернуть переменную вне функции JavaScript, которая находится внутри функции? - PullRequest
2 голосов
/ 02 января 2012

Итак, у меня есть

  function find_coord(lat, lng) {
              var smart_loc;
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
        });

        return smart_loc;
}

Я хочу вернуть переменную / объект smart_loc, но он всегда равен нулю, поскольку область действия функции (результаты, состояние) не достигает значения smart_loc, объявленного в функции find_coord. Так как же вывести переменную внутри функции (результаты, статус)?

1 Ответ

0 голосов
/ 02 января 2012

Вы можете сделать:

var smart_loc;

function find_coord(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }
    });
}

Или, если вам нужно запустить функцию при изменении smart_loc:

function find_coord(lat, lng, cb) {
          var smart_loc;
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }

        cb(smart_loc);
    });
}

затем позвоните:

find_coord(lat, lng, function (smart_loc) {
    //
    // YOUR CODE WITH 'smart_loc' HERE
    //
});
...