jquery - Odd behavior of Static Variable of JavaScript closure programming -


why javascript code produce funny result? @ 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> 

you're incrementing row in every cell:

this.getcell = function(){     var rowid = tablerow.id;     var cellid = tablecell.id;     // row id gets updated      tablerow.id = tablerow.id + 1;     tablecell.id = tablecell.id + 1; 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -