0
這段JavaScript代碼爲什麼產生這個有趣的結果?看看RowID和CellID。JavaScript封閉編程的靜態變量的奇怪行爲
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>
你可以把這個中的jsfiddle?一段代碼對於調試並不是那麼有趣。我們如何猜測ClosureAccessStaticVariable.js中的內容? – frenchie 2013-05-02 20:09:51
你爲什麼認爲結果很有趣?你還有什麼期望? – Bergi 2013-05-02 21:45:24
Frenchie:ClosureAccessStaticVariable.js中有什麼是這段代碼,只是把它作爲一個html頁面,所以你可以直接運行它爲.html文件。 – 2013-05-15 19:30:19