Javascript 未捕获类型错误:对象[对象对象]没有方法';绘制';比赛。js:202平局
我看过这个问题的许多其他答案,但都找不到答案 问题似乎是它没有在我的game.js文件中识别全局世界 html文件的顺序正确Javascript 未捕获类型错误:对象[对象对象]没有方法';绘制';比赛。js:202平局,javascript,html,canvas,Javascript,Html,Canvas,我看过这个问题的许多其他答案,但都找不到答案 问题似乎是它没有在我的game.js文件中识别全局世界 html文件的顺序正确 <script src="js/world.js"></script> <script src="js/game.js"></script> 在game.js中--罪魁祸首很可能就在这里 请注意,以下两个函数均未嵌套在任何对象中: var World; function init() { // Declare t
<script src="js/world.js"></script>
<script src="js/game.js"></script>
在game.js中--罪魁祸首很可能就在这里
请注意,以下两个函数均未嵌套在任何对象中:
var World;
function init() {
// Declare the canvas and rendering context
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
localPlayer = new Player(startX, startY); //WORKS CORRECTLY
World = new World(); //SHOULD ALSO WORK CORRECTLY
init函数的外部是
function draw() {
// Wipe the canvas clean
ctx.clearRect(0, 0, canvas.width, canvas.height);
World.draw(ctx);
// Draw the local player
// Draw the remote players
var i;
for (i = 0; i < remotePlayers.length; i++) {
remotePlayers[i].draw(ctx);
};
localPlayer.draw(ctx);
};
函数绘图(){
//把画布擦干净
clearRect(0,0,canvas.width,canvas.height);
世界绘画(ctx);
//吸引本地玩家
//吸引远程玩家
var i;
对于(i=0;i
在World.draw(ctx)中,我得到了错误
未捕获的类型错误:对象[Object Object]没有“draw”游戏的方法。js:202 draw
如果你需要更多的细节,我很乐意效劳。我会发布我所有的代码,只是它非常大。如果您使用
draw()
作为实例方法,您应该将其定义为:
var World = function(){
this.draw = function(ctx) {
ctx.drawImage(bg1, 100, 100);
};
};
此
关键字允许在世界
对象之外引用函数
使用
var
将可见性限制在函数World
的范围内。如果需要多个World
实例,则需要让构造函数将函数导出为属性(在上此
)-请参阅以了解私有变量的差异。然后不要将实例写入与构造函数相同的变量
function World(){
this.draw = function(ctx) {
ctx.drawImage(bg1, 100, 100);
};
}
var world, ctx;
function init() {
// Declare the canvas and rendering context
var canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
world = new World(ctx);
…
}
function draw() {
world.draw(ctx);
…
}
但是,如果您只需要一个静态模块(singleton),那么不要考虑初始化,只需使用分配给World
的对象文本,它将充当名称空间。这就是@fahadash的建议:
World = {
draw: function(ctx) {
ctx.drawImage(bg1, 100, 100);
}
};
var ctx;
function init() {
// Declare the canvas and rendering context
var canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
// no World initialisation here! Do not try to call `new World`!
…
}
function draw() {
World.draw(ctx);
…
}
看起来是在
init()
之前调用了draw()
函数。请注意,您的World
构造函数没有在返回的实例上公开draw
方法(属性),只是具有该名称的一些私有变量。看见您不应该将World
实例分配给World
变量,从而覆盖构造函数。啊,完美!谢谢
World = {
draw: function(ctx) {
ctx.drawImage(bg1, 100, 100);
}
};
var ctx;
function init() {
// Declare the canvas and rendering context
var canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
// no World initialisation here! Do not try to call `new World`!
…
}
function draw() {
World.draw(ctx);
…
}