我正在使用Eloquent Javascript chapter跟随我从头开始创建自己的浏览器游戏。所有这些代码都不是我的,它是本书中提供的代码片段的汇编。到目前为止,代码应该只显示背景和问题。这是不一个完整的游戏
以下是我们关注的代码片段:
/*
Constructor
@param parent: DOM object, probably a <div> that you want the game to go in
@param level: a new Level object
*/
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(elt("div", "game")); //appendChild returns the appended element
this.level = level; //the level object created w/ constructor
this.wrap.appendChild(this.drawBackground()); //draws the background (only once)
this.actorLayer = null; // hold the actors and is used by drawFrame() so they can be replaced/removed
this.drawFrame();
}
var scale = 20; // number of pixels per unit
DOMDisplay.prototype.drawBackground = function() {
var table = elt("table", "background"); // makes table element with className "background"
table.style.width = this.level.width * scale + "px";
this.level.grid.forEach(function(row) { // remember that grid = [[gridLine],[gridLine],[gridLine]]
var rowElt = table.appendChild(elt("tr")) // appends and creates a table row for each [gridLine]
rowElt.style.height = scale + "px"; // each row is 1 unit tall (which is 20 px)
row.forEach(function(type) { // for each row.. remember a row consists of all the item types
rowElt.appendChild(elt("td", type)); //for the current rowElt, append each item type as td
});
});
return table;
};
// start it up
simplelevel =new Level(simpleLevelPlan)
DOMDisplay(document.body, simplelevel)
在浏览器中运行此代码后,我收到以下错误,并且不知道原因:
TypeError: undefined is not a function (evaluating 'this.drawBackground()')
以下是JS Fiddle,您可以使用所有代码。