javascript - Why inline function doesn't catch a variable -
this question has answer here:
i want callback called when user clicks on marker. i've figured out if use inline defined function, variable want use has value corresponding last used value. in code below it's last value of data
array.
<!doctype html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>simple markers</title> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script> <script> var data = [ {name: 'limanowskiego 1', lat: 53.785418, long: 20.4907734}, {name: 'partyzantów 12', lat: 53.782255, long: 20.484778}]; function createcallback(p) { return function(e) { console.log(p); }; } function initialize() { var mapoptions = { zoom: 14, center: new google.maps.latlng(53.785418, 20.4907734) }; var map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); var infowindow = new google.maps.infowindow({ content: "test string" }); (var i=0; < data.length; i++) { var point = data[i]; var mylatlng = new google.maps.latlng(point.lat, point.long); var marker = new google.maps.marker({ position: mylatlng, map: map, title: point.name, }); google.maps.event.addlistener(marker, 'click', function(e) { console.log(point); }); } } google.maps.event.adddomlistener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"></div> </body> </html>
if replace listener registration by:
google.maps.event.addlistener(marker, 'click', createcallback(point));
it works expected.
my suspicion aren't telling anonymous function here point is.
google.maps.event.addlistener(marker, 'click', function(e) { console.log(point); //point?? point? });
you solve adjusting parameters accordingly...
google.maps.event.addlistener(marker, 'click', function(e, point) { //oh, point! console.log(point); });
if don't understand why is, it's because point
declared in surrounding function local variable, not global variable (which best!).
when create new, anonymous function, creates own scope, , doesn't know other function's point
. tell anonymous function point use, can pass in parameter, hence answer above.
Comments
Post a Comment