gpt4 book ai didi

javascript 原型(prototype)...不是一个函数

转载 作者:行者123 更新时间:2023-12-03 09:15:35 24 4
gpt4 key购买 nike

我总是收到这样的错误:player.draw() 不是一个函数,但我找不到问题所在。 Player 类存在,但绘图方法不存在:( 希望我可以为您提供更多详细信息,但没有更多详细信息。感谢您的帮助,这是代码:

var version = "0.0.1";
var is_playing = false;

init();
function init(){
background_canvas = document.getElementById("background-canvas");
background_ctx = background_canvas.getContext("2d");
main_canvas = document.getElementById("main-canvas");
main_ctx = main_canvas.getContext("2d");

requestaframe = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60); };
})();

player = new Player();
start_loop();
}

function mouse(e){
var x = e.pageX - document.getElementById("game-holder").offsetLeft;
var y = e.pageY - document.getElementById("game-holder").offsetTop;
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
}

function Player(){
this.color = "yellow";
}

Player.prototype.draw = function(){
main_ctx.fillStyle = this.color;
main_ctx.arc(205, 70, 25, 0, 2*Math.PI);
main_ctx.fill();
};

function clearStage(){
main_ctx.clearRect(0, 0, 800, 600);
}

function start_loop(){ is_playing = true; loop(); }
function stop_loop(){ is_playing = false; }

function loop(){
clearStage();
main_ctx.fillStyle = "blue";
main_ctx.fillRect(175, 100, 450, 450);
player.draw();
if(is_playing) requestaframe(loop);
}

最佳答案

您尝试使用提升,但似乎没有完全理解它。

一般来说,提升会将函数和变量声明(而不是赋值!)移动到当前作用域的顶部。这就是为什么您可以在实际声明之前调用 init() 方法的原因。

所以稍微精简一下你的代码,看起来像这样

init();
function init() { ... }

function Player() { ... }

Player.prototype.draw = ...;

提升后(代码的评估方式)如下所示:

function init() { ... }

function Player() { ... }

init();

Player.prototype.draw = ...;

所以你可以清楚地看到,当你第一次调用 init() 时,draw() 方法还没有附加到 Player 原型(prototype)上,因此它是未定义的。

简单的解决方案是更改代码的顺序并将 init() 调用移至底部。

关于javascript 原型(prototype)...不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com