JavaScript闭包编程的静态变量的奇怪行为

时间:2013-05-02 20:02:02

标签: javascript jquery closures

为什么这个JavaScript代码会产生这个有趣的结果?查看RowID和CellID。

Result: 
[R0C0]: Apple   [R1C1]: 400
[R2C0]: Google  [R3C1]: 700


    <html>
     <head>
      <script src="ClosureAccessStaticVariable.js" type="text/javascript"></script>
      <script src="jquery-1.9.1.js" type="text/javascript"></script>
     </head>
     <body>
      <div id="panelTable"></div>
      <script>
        function Table(dataRows){
        var rows = [];
        this.GetTable = function(){
            var table = $("<table>");
            $(rows).each(function(){
                table.append(this.GetRow());
            });
            return table;
        }
        function init(){
            $(dataRows).each(function(index){
                rows[index] = new TableRow(this);
            });
        }
        function TableRow(rowData){
            var cells = [];
            this.GetRow = function(){
                var row = $("<tr>");
                $(cells).each(function(){
                    row.append(this.GetCell());
                });
                return row;
            }
            function init(){
                var i=0;
                for(var cellName in rowData){
                    cells[i] = new TableCell(rowData[cellName]);
                    i++;
                }
            }
            function TableCell(text){
                this.GetCell = function(){
                    if(TableRow.ID == undefined)
                        TableRow.ID = 0;
                    if(TableCell.ID == undefined)
                        TableCell.ID = 0;

                    var rowId = TableRow.ID;
                    var cellId = TableCell.ID;
                    TableRow.ID = TableRow.ID + 1;
                    TableCell.ID = TableCell.ID + 1;
                    return $("<td style='border:1px solid lightgray;padding:2px;'>").html("[R"+rowId+"C"+cellId+"]: "+text);
                }
            }
            init();
        }
        init();
        }
        var data = [ { Name: "Apple", Value: 400}, {Name: "Google", Value: 700}];
        var table = new Table(data);
        var tableDom = table.GetTable();
        $("#panelTable").append(tableDom);
    </script>
     </body>
    </html>

1 个答案:

答案 0 :(得分:0)

您正在递增每个单元格中的行:

this.GetCell = function(){
    var rowId = TableRow.ID;
    var cellId = TableCell.ID;
    // The row ID gets updated 
    TableRow.ID = TableRow.ID + 1;
    TableCell.ID = TableCell.ID + 1;