L
liketofindoutwhy
I did some animation using
var oDiv = {};
oDiv.x = 100;
oDiv.y = 100;
oDiv.node = document.getElementById('divImage');
oDiv.node.style.position = "absolute";
oDiv.doAnimation = function() {
oDiv.x += 1;
oDiv.y += 1;
oDiv.node.style.top = oDiv.y + 'px';
oDiv.node.style.left = oDiv.x + 'px';
setTimeout(oDiv.doAnimation, 33);
}
and it works fine. When it is changed to the traditional class
definition, then it fails:
function Animation() {
this.x = ...
etc...
this.doAnimation = function() {
// do something
// set delay
setTimeout(this.doAnimation, 33);
}
}
oDiv = new Animation();
oDiv.doAnimation();
which will fail. The second time when the doAnimation() is called, it
seems that it doesn't have a concept of this.x, etc.
It is the same if I use the more popular way of defining a class by
moving the function out:
function Animation() {
this.x = ...
etc...
}
Animation.prototype.doAnimation = function() {
// do something
}
and it is the same, the second time when doAnimation() is invoked by
the setTimeout, it doesn't have a concept of this.x.
Does someone know what it is? hm... I don't need to use prototype.js
and use something like doAnimation.bind(this) ? Can it be a self-
contained script that doesn't rely on other framework? Thanks.
var oDiv = {};
oDiv.x = 100;
oDiv.y = 100;
oDiv.node = document.getElementById('divImage');
oDiv.node.style.position = "absolute";
oDiv.doAnimation = function() {
oDiv.x += 1;
oDiv.y += 1;
oDiv.node.style.top = oDiv.y + 'px';
oDiv.node.style.left = oDiv.x + 'px';
setTimeout(oDiv.doAnimation, 33);
}
and it works fine. When it is changed to the traditional class
definition, then it fails:
function Animation() {
this.x = ...
etc...
this.doAnimation = function() {
// do something
// set delay
setTimeout(this.doAnimation, 33);
}
}
oDiv = new Animation();
oDiv.doAnimation();
which will fail. The second time when the doAnimation() is called, it
seems that it doesn't have a concept of this.x, etc.
It is the same if I use the more popular way of defining a class by
moving the function out:
function Animation() {
this.x = ...
etc...
}
Animation.prototype.doAnimation = function() {
// do something
}
and it is the same, the second time when doAnimation() is invoked by
the setTimeout, it doesn't have a concept of this.x.
Does someone know what it is? hm... I don't need to use prototype.js
and use something like doAnimation.bind(this) ? Can it be a self-
contained script that doesn't rely on other framework? Thanks.