jon*_*opf 2 javascript variables class
我是JavaScript的新手.因此这个问题有点令人困惑.我试图简单地定义一个计数器并在类方法中增加它,但它的行为不像我期望的那样.专门console.log(this.tick_count);打印undefined.
JavaScript的:
function Game() {
this.fps = 50;
this.ticks = 3;
this.current_time = (new Date).getTime();
this.draw_object = document.getElementById('game_canvas').getContext('2d');
this.tick_count = 0;
}
Game.prototype.update = function (time) {
this.current_time = time;
}
Game.prototype.draw = function () {
this.draw_object.fillRect(10, 10, 55, 50);
}
Game.prototype.run = function () {
self.setInterval(this.tick, 1000 / (this.fps * this.tick));
}
Game.prototype.tick = function () {
this.tick_count++;
console.log(this.tick_count);
}
function start_game() {
var game_object = new Game();
game_object.run();
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<body onload="start_game()">
<canvas id="game_canvas" width="1024" height="1024"></canvas>
</body>
Run Code Online (Sandbox Code Playgroud)
来自Python背景我觉得这个行为很奇怪.我应该如何正确设置我的类变量?
这就是正在发生的事情.
基本上,您的tick功能不再在game_object对象的上下文中运行.这可能听起来很奇怪来自Python背景,但基本上该this对象设置为其他东西.
那它是什么设置的?容易,window对象,我们怎么知道这个?因为setInterval上下文是window对象.
移动示例代码将无法在下面正确格式化
绑定示例
setInterval(this.tick.bind(this), 1000 / (this.fps * this.tick)); //Native (JS v1.8+)
$.proxy(this.tick, this); //jQuery
_.bind(this.tick, this); //underscore / lodash
Run Code Online (Sandbox Code Playgroud)
显式上下文示例
Game.prototype.run = function () {
var _this = this;
setInterval(function() {
//So what is this at the moment? window.
//Luckily we have a reference to the old this.
_this.tick();
}, 1000 / (this.fps * this.tick));
};
Run Code Online (Sandbox Code Playgroud)
你可以绕过这两种方式.
| 归档时间: |
|
| 查看次数: |
5104 次 |
| 最近记录: |