gpt4 book ai didi

javascript - Context2D 定义后未定义

转载 作者:行者123 更新时间:2023-12-01 01:35:17 25 4
gpt4 key购买 nike

我有一个简单的 javascript 构造函数,它构造一个应该绘制 conways 生命游戏的对象:

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是未定义的。

为什么我可以清楚地看到它之前已经定义了,但它是未定义的?

最佳答案

您在 update 函数中引用了错误的 this

只需绑定(bind)正确的上下文(即 GameOfLife 构造函数的上下文)

this.interval = setInterval(this.update.bind(this), 20);

或者使用箭头函数让它继承外部作用域。

this.update = () => {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

关于javascript - Context2D 定义后未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52889325/

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