在主程序中,我随机选择一个我想要动画的对象,所以我用对象作为参数调用该函数。第一个循环是好的,x
设置得很好,但在下一个回合它变成了undefined
。
像这样的东西:
var anim = {
mainFunc: function(x) {
anim.update(x);
anim.redraw(x);
window.requestAnimationFrame(anim.mainFunc);
},
update: function(x) {
},
redraw: function(x) {
}
};
var n=Math.floor(Math.random() * (ArrayOfAnimObject.length));
anim.mainFunc(ArrayOfAnimObject[n]);
您需要创建一个引用或将函数调用包装在另一个函数中,如下所示:
mainFunc: function(x) {
anim.update(x);
anim.redraw(x);
window.requestAnimationFrame(function() {
anim.mainFunc(x);
});
}
你也可以使用.bind
。
mainFunc: function(x) {
anim.update(x);
anim.redraw(x);
window.requestAnimationFrame(anim.mainFunc.bind(anim,x));
}
最好的可能是避免必须这样做。
允许你这样做的解决方案需要你创建一个新的函数(无论是@kalley的答案中的匿名包装器,还是来自@ArmyWillHe的绑定的函数)。
在动画循环中,您希望尽可能保留较少可收集的对象,以便垃圾收集器不必在动画运行时启动,在发生时会消耗几帧。
为了执行此操作,您可以使用不同的策略,但是例如在OP中公开的情况下,此x
参数可能应该直接附加到anim
对象:
var anim = {
mainFunc: function() {
anim.update();
anim.redraw();
window.requestAnimationFrame(this.mainFunc);
},
update: function() {
this.x ++;
},
redraw: function() {
log.textContent = this.x;
}
};
// replace it with a bound function only once
anim.mainFunc = anim.mainFunc.bind(anim);
anim.x = 0; // attach the parameter to the anim object
anim.mainFunc();
<pre id="log"></pre>
也可能更喜欢将此参数保持为调用者和anim
可用的变量:
(function() {
var anim = {
mainFunc: function() {
anim.update();
anim.redraw();
window.requestAnimationFrame(anim.mainFunc);
},
update: function() {
x ++;
},
redraw: function() {
log.textContent = x;
}
};
var x = 0; // available for both us and anim's method
anim.mainFunc();
})();
<pre id="log"></pre>