我一直在阅读有关谷歌地图 API 中的函数闭包的内容。他们使用以下示例:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922 }
});
var bounds = {
north: -25.363882,
south: -31.203405,
east: 131.044922,
west: 125.244141
};
// Display the area between the location southWest and northEast.
map.fitBounds(bounds);
// Add 5 markers to map at random locations.
// For each of these markers, give them a title with their index, and when
// they are clicked they should open an infowindow with text from a secret
// message.
var secretMessages = ['This', 'is', 'the', 'secret', 'message'];
var lngSpan = bounds.east - bounds.west;
var latSpan = bounds.north - bounds.south;
for (var i = 0; i < secretMessages.length; ++i) {
var marker = new google.maps.Marker({
position: {
lat: bounds.south + latSpan * Math.random(),
lng: bounds.west + lngSpan * Math.random()
},
map: map
});
attachSecretMessage(marker, secretMessages[i]);
}
}
// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with the secret message.
function attachSecretMessage(marker, secretMessage) {
var infowindow = new google.maps.InfoWindow({
content: secretMessage
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
他们在每次循环迭代中定义marker
变量。
Question: Why doesn't the
marker
declared in previous declaration get overridden by themarker
declared in the next loop iteration? Why are multiple markers shown on the map? Since there is only onemarker
variable, there should be only one `marker shown on the map.
最佳答案
marker 是一个变量,每次循环迭代时,都会创建一个新对象 使用新运算符
现在,每次更新标记变量时,它都会引用不同的对象,只是变量赋值发生变化,并且对象仍在内存中
考虑一个例子
var student = {
marks: 100
}
var student1 = student;
student = {
marks: 200
}
console.log(student1.marks); //100
console.log(student.marks); //200
看到对象仍在内存中,只是我的学生变量引用发生了变化
关于javascript - javascript中可以有多个同名对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37983819/