我一直在研究这个代码,但我很困惑为什么它不起作用。我创建了三个" Geocache "对象并将它们分配给名为' 缓存'的数组。为了测试,我已经分配了变量" value "到缓存的索引1中的任何内容。然后我定义了变量" tease "作为' lony ' 值的属性。
function Geocache (lat, lon, disc){
this.laty=lat;
this.lony=lon;
this.disc=disc;
}
var loc1=new Geocache(43.77416104496804, -79.50804830784301, "lifesci building");
var loc2=new Geocache(43.77381242916627, -79.50533927673797, "lassonde building");
var loc3=new Geocache(43.77305321438563, -79.50353146786193, "vari hall");
var caches=[loc1,loc2,loc3];
var value = caches[1];
var tease=value.lony;

这应该吐出" -79.505的价值......"但相反,我得到一个" undefined"在预览中。 有人可以帮我弄清楚这段代码有什么问题,因为我似乎无法弄明白。
答案 0 :(得分:1)
这是代码,在代码段的javascript部分使用javascript。
修复使用自我调用函数来阻止全局泄漏。
function Geocache (lat, lon, disc){
this.laty=lat;
this.lony=lon;
this.disc=disc;
}
(function () {
var loc1=new Geocache(43.77416104496804, -79.50804830784301, "lifesci building");
var loc2=new Geocache(43.77381242916627, -79.50533927673797, "lassonde building");
var loc3=new Geocache(43.77305321438563, -79.50353146786193, "vari hall");
var caches=[loc1,loc2,loc3];
var value = caches[1];
var tease=value.lony;
console.log(tease);
})();