学习 javascript,我想获得有关自调用函数的反馈。
我读到创建全局变量不是要走的路。
这是原版
// Footer of page
<script>
var lat = 51.505 // retrieved from db
var lon = -0.09 // retrieved from db
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([lat, lon]).addTo(map)
.bindPopup('You are here.')
.openPopup();
</script>
重构
// Footer of page
<script>
(function(){
var createMap = function() {
var lat = 51.505 // retrieved from db
var lon = -0.09 // retrieved from db
var map = L.map('map').setView([lat, lon], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([lat, lon]).addTo(map)
.bindPopup('You are here.')
.openPopup();
}(); // createMap function self invocation
})(); // anonymous function self invocation
</script>
我不确定我的重构版本是否有意义,因为我在var createMap
自调用匿名函数中创建了一个函数。
我不想用从数据库中检索到的lat
&变量来混淆全局命名空间。lon
更新
或者以下内容会更有意义。一个自调用匿名函数,其中包含变量和代码。这不会干扰或将分配的变量添加到全局命名空间吗?
// Footer of page
<script>
(function(){
var lat = 51.505 // retrieved from db
var lon = -0.09 // retrieved from db
var map = L.map('map').setView([lat, lon], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([lat, lon]).addTo(map)
.bindPopup('You are here.')
.openPopup();
})(); // anonymous function self invocation
</script>