具有可变范围的JavaScript循环问题

时间:2011-06-16 20:49:02

标签: javascript jquery variables scope each

所以,我有这个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/

上找到

在循环结束时,任何mylist[x].site的{​​{1}}都指向我的数据项的同一个实例,我该如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

问题是每个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
}

这会将 new 对象分配给每个 new 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返回现有对象,这确实很有趣。)

答案 1 :(得分:0)

你需要在.each之外声明var引脚吗? 然后在.each中将其设置为新的。

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); }
 });

答案 2 :(得分:0)

考虑到你在一个函数中,我会说是的,当然它们都指向同一个对象,因为你只是通过引用传递。环顾四周之后我偶然发现了这个问题 - http://my.opera.com/GreyWyvern/blog/show.dml/1725165 - 但看起来没有一个直接选择来克隆Javascript对象。

也许你最好的方法是编写一个克隆输入对象并将其作为新实例返回的函数?

答案 3 :(得分:0)

在阅读了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;
 });