[英]What is this function doing for Game Of Life project
我正在從事“人生游戲”項目。 建議我創建自己的迭代函數,以便在需要迭代時可以使用它。 這是我本節的當前代碼:
var onCellClick = function (event) {
// how to set the style of the cell when it's clicked
if(this.className === "dead") {
this.className = "alive";
} else {
this.className = "dead";
}
};
//applies the onclick listener to the entire board.
this.iterateCells(function(cell, x, y) {
cell.onclick = onCellClick;
});
GameOfLife.prototype.iterateCells = function(iterator) {
for(var y=0; y < this.height; y++) {
for(var x=0; x < this.width; x++) {
var currentCell = document.getElementById(x+"-"+y);
iterator(currentCell, x, y);
}
}
};
我正在做的是使我的20/20網格中的每個單元格都激活“ onCellClick”功能。
我不確定
a)在迭代單元格函數中,作為參數傳遞的迭代器是什么? 有什么價值? 這是我最大的困惑。
b)當this.iterateCells(function(cell,x,y)作為迭代器參數傳遞的實際功能是什么?
如果您需要查看http://jsfiddle.net/8Tut6/3/上正在發生的事情的更多信息,這是項目的鏈接。
函數是JavaScript中的一等公民,這意味着您可以將它們存儲在變量中並將它們作為參數傳遞。 例如:
// this function executes a function that is passed as a parameter
function execute(func)
{
func();
}
function hello()
{
alert("Hello, World!");
}
execute(hello);
execute(function () { alert("Hello again!"); });
此代碼提醒“世界您好!” 然后“再次問好!”。
專門回答您的問題:
a) iterator
為function(cell, x, y) { cell.onclick = onCellClick; }
function(cell, x, y) { cell.onclick = onCellClick; }
b)該函數被iterateCells
多次iterateCells
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.