[英]JavaScript Loop issue with variable scope
所以,我有这个jQuery .each
循环,并且在大多数情况下它按预期工作; 有一个问题,但首先是循环:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function Pushpin(){}
Pushpin.prototype.XZX = {
site: null,
getHtmlDescription: function () {
var html = '<b id="infoboxTitle" style="position:absolute; top:10px; left:10px; width:220px;">' + this.site.Name + '</b>';
html += '<a id="infoboxDescription" style="position:absolute; top:30px; left:10px; width:220px; height:120px;">{0}</a>';
var description = 'Headcount: ' + this.site.Headcount + '<br />';
description += 'Leases: ' + this.site.LeaseCount + '<br />';
html = html.replace('{0}', description);
return html;
}
};
var data = [
{"Address":{"City":"Atlanta","Country":"USA","County":"","Latitude":33.9882404987503,"Longitude":-84.1629638209203,"Region":"Southeast","State":"GA","StreetAddress":"Atlanta 177","ZipCode":"30096"},"Headcount":0,"ImageBytes":null,"ImageRefPath":"","LeaseCount":1,"Leases":null,"Name":"Atlanta","NextExpire":"\/Date(1495083600000-0500)\/","Number":"1052","PrimaryUse":"Garage","PropertyID":"OMNI","RecID":32839,"RecordID":1004,"RentableSquareFootage":22000,"SiteRecordID":"DEMO_29626","SiteTotalDollars":0,"Status":null,"Type":"LSE"},
{"Address":{"City":"Bellevue","Country":"USA","County":"","Latitude":47.6043250620083,"Longitude":-122.14236047437,"Region":"Northwest","State":"WA","StreetAddress":"Seattle 51","ZipCode":"98007"},"Headcount":0,"ImageBytes":null,"ImageRefPath":"","LeaseCount":1,"Leases":null,"Name":"Bellevue","NextExpire":"\/Date(1260424800000-0600)\/","Number":"1078","PrimaryUse":"Tower","PropertyID":"OMNI","RecID":32865,"RecordID":1027,"RentableSquareFootage":7652,"SiteRecordID":"DEMO_275651","SiteTotalDollars":0,"Status":null,"Type":"LSE"}
];
var mylist = [];
$.each(data, function (i, item) {
try {
var pin = new Pushpin();
pin.XZX.site = item;
mylist.push(pin);
} catch (e) { alert (e); }
});
$(document).ready(function() {
$('#btnAlert').click(function () {
$('#content').html(mylist[$('#index').val()].XZX.getHtmlDescription());
} );
});
</script>
</head>
<body >
<div style="margin-left:auto; margin-right:auto; width:300px;">
<div style="position:relative; width:250px;">
<select id="index">
<option>0</option>
<option>1</option>
</select>
<input type="submit" id="btnAlert"/>
</div>
<div id="content" style="position:relative;width:250px;"></div>
</div>
</body>
</html>
也可以在jsfiddle上找到: http : //jsfiddle.net/M8YS2/
在循环结束时,任何x
mylist[x].site
都指向我的数据项的同一个实例,我该如何解决这个问题呢?
问题是每个pin.XYZ
都是同一个对象 - 即Pushpin.prototype.XYZ
。
简单的“修复”是使用:
var pin = new Pushpin(...)
pin.XYZ = {
site: item
// the following will get tedious fast, consider one of the "property copy"
// implementations floating about -- including jQuery.extend
getHtmlDescription: Pushpin.prototype.XYZ.getHtmlDescription
}
这将为每个新的 Pushpin对象的XYZ
属性分配一个新对象。 当然,这也可以设计得不同:)
最起码,移动XYZ
关闭Pushpin.prototype对象-这将允许它很好地视为一个对象(该方式this
传递关于其实可以更近了,不可能悬掉原型的目的在于功能访问原型适用的对象的实例数据); 结束代码可能看起来像:
// We .. "wrap" the real Pushpin constructor
// somewhere global after Bing Mapi JS loaded
Pushpin = (function (bingPushpin) {
return function Pushpin (...) {
var pin = new bingPushpin(...)
pin.XYZ = new XYZ()
// trick of "returning" from ctor
return pin
}
})(PushPin)
// ...
var pin = new Pushpin(...)
pin.XYZ.site = item
快乐的编码。
更新前的答案:
这实际上不是一个范围问题 - 没有创建无意的闭包,每个表达式都经过严格评估。
我怀疑还有另一个问题,例如意外输入(数据包含一堆相同的项目 )或有缺陷的假设(这样的对象被神奇地克隆)或某些不相关的东西。
快乐的编码。
分析:
var mylist = [];
$.each(data, function (i, item) {
// creates new object
var pin = new Pushpin(x, y);
// property of new object assigned
// remember that no "duplication" is occurring
pin.site = item;
// new object pushed to array
mylist.push(pin);
});
因此,没有pin
是相同的, 但是每个循环的item
可能会评估为相同的对象 。 ( 唯一的例外是如果Pushpin构造函数使用return
来返回一个现有的对象,这确实很有趣。)
你需要在.each之外声明var引脚吗? 然后在.each中将其设置为new。
var pin;
var mylist = [];
$.each(data, function (i, item) {
try {
pin = new Pushpin(x, y);
pin.site = item;
mylist.push(pin);
} catch (e) { alert (e); }
});
考虑到你在一个函数中,我会说是的,当然它们都指向同一个对象,因为你只是通过引用传递。 环顾四周之后,我偶然发现了这个问题 - http://my.opera.com/GreyWyvern/blog/show.dml/1725165 - 但看起来没有一个直接的克隆Javascript对象的选项。
也许你最好的方法是编写一个克隆输入对象并将其作为新实例返回的函数?
在阅读了MoarCodePlz的答案之后,我想也许这可以帮助绕过“参考”问题。 虽然没有验证。
var mylist = [];
$.each(data, function (i, item) {
// Creates the new object as a part of yourlist
mylist.push(new Pushpin(x, y));
// property of new object assigned item
mylist[x].site = item;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.