从新对象中运行requestAnimationFrame

JVE*_*999 7 javascript three.js requestanimationframe

我在运行动画时遇到了麻烦.这是在里面var ob1 = function() {};.当被调用时,它会运行一段时间,然后我得到错误Uncaught RangeError: Maximum call stack size exceeded.但是,这种相同的结构在对象之外运行没有问题.

/////////////// Render the scene ///////////////
this.render = function (){

        renderer.render(scene,camera);
        if(isControls == true) controls.update(clock.getDelta());
        this.animate();
        //console.log(true);
        requestAnimationFrame(this.render());
}

/////////////// Update objects ///////////////
this.animate = function (){
        console.log("!");
}
Run Code Online (Sandbox Code Playgroud)

bfa*_*tto 17

你应该传递一个函数引用requestAnimationFrame,而不是调用函数:

requestAnimationFrame(this.render);
Run Code Online (Sandbox Code Playgroud)

由于你在this里面使用render,你可能需要bind:

requestAnimationFrame(this.render.bind(this));
Run Code Online (Sandbox Code Playgroud)

您的版本导致堆栈溢出(该函数同步调用自身,直到调用堆栈已满).


  • 您不希望以这种方式使用绑定,因为每次调用绑定时都会创建一个新的函数对象。相反,您希望在初始化时预先绑定,如“const render = this.render.bind(this);”,然后在循环中调用“requestAnimationFrame(render)”。你也可以用反应的方式来做,在你的构造函数中做 `this.render = this.render.bind(this);` 然后你可以调用 `requestAnimationFrame(this.render);` (2认同)