我有一个简单的javascript构造函数,该函数构造一个应该绘制生活游戏的对象:
function startGame() {
var myGameOfLife = new GameOfLife();
myGameOfLife.initialize(500, 500);
}
function GameOfLife() {
this.canvas = document.createElement("canvas");
this.initialize = function(width, height) {
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(this.update, 20);
}
this.update = function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
</script>
</body>
</html>
当我调试该脚本时,我可以看到在初始化函数this.context
中已分配了该脚本。但是,当间隔调用更新函数时,this.context
是不确定的。
当我可以清楚地看到它之前被定义时,为什么它未定义?
答案 0 :(得分:2)
您在this
函数中指的是错误的update
。
只需绑定正确的上下文(即GameOfLife
构造函数的上下文)
this.interval = setInterval(this.update.bind(this), 20);
或使用箭头函数以使其继承外部范围。
this.update = () => {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}