英文:
Create an object in Javascript and animiate it
问题
我想在JavaScript中创建对象,并使它们能够自行动画,即不在外部的动画函数中驱动它们。
<script>
const Canvas = document.getElementById("diagramCanvas");
const CanvasContext = Canvas.getContext('2d');
const width = Canvas.width, height = Canvas.height;
var cmTID;
function SelfMovingBox() {
this.x = width;
this.animate = function() {
CanvasContext.clearRect(this.x, 10, 100, 20);
this.x -= 10;
CanvasContext.save();
CanvasContext.strokeStyle = 'blue';
CanvasContext.strokeRect(this.x, 10, 100, 20);
CanvasContext.restore();
setTimeout(this.animate, 100);
}
}
let box = new SelfMovingBox();
box.animate();
</script>
但是这个"循环"只会运行一次。为什么它会在没有错误的情况下终止,我如何在对象中没有在外部的动画函数循环中被外部调用的 this.move() 函数的情况下实现这一点?
谢谢!
英文:
I'd like to create objects in Javascript and have them be able to animate themselves, i.e. not in an external animation function driving them.
<script>
const Canvas = document.getElementById("diagramCanvas");
const CanvasContext = Canvas.getContext('2d');
const width = Canvas.width, height = Canvas.height;
var cmTID;
function SelfMovingBox() {
this.x = width;
this.animate = function() {
CanvasContext.clearRect(this.x,10,100,20);
this.x -= 10;
CanvasContext.save();
CanvasContext.strokeStyle = 'blue';
CanvasContext.strokeRect(this.x,10,100,20);
CanvasContext.restore();
setTimeout(this.animate, 100);
}
}
let box = new SelfMovingBox();
box.animate();
</script>
But this "loop" will not run more than once. Why does it terinate with no error, and how could I achieve this, without a this.move() function in the object invoked externally in an animation function loop?
Thanks!
答案1
得分: 1
这似乎是与this的使用有关的问题。
只看相关部分:
function SelfMovingBox() {
this.x = width;
this.animate = function() {
this.x -= 10;
}
}
当你设置this.x = width时,this指的是SelfMovingBox实例,因为你是用new调用该函数。
但在animate中,this指的是Window,这是JavaScript函数的默认(奇怪)行为。
你有几个选项:使用箭头函数() => {}以获得词法作用域的this:
this.animate = () => {
this.x -= 10;
}
或使用bind来显式绑定this:
this.animate = (function() {
this.x -= 10;
}).bind(this);
英文:
This looks like a problem with the use of this.
Looking at just the relevant parts:
function SelfMovingBox() {
this.x = width;
this.animate = function() {
this.x -= 10;
}
}
When you set this.x = width, this refers to the SelfMovingBox instance, because you are calling the function with new.
But in animate, this is referring to Window, which is JavaScript's default (weird) behavior for functions.
You have a few options: use an arrow function () => {} for lexically scoped this:
this.animate = () => {
this.x -= 10;
}
or use bind to explicitly bind this:
this.animate = (function() {
this.x -= 10;
}).bind(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论