JavaScript类中的递归调用(requestAnimationFrame)

8

我有一个简单的类,用于在three.js中管理场景。我正在遇到requestAnimationFrame循环查找函数引用的问题。我知道我在这里缺少一些基本的东西,陷入了某种“this”噩梦。我需要使用bind或call来传递此引用以便requestAnimationFrame吗?

var THREE = THREE || {};
var SceneBuddy = SceneBuddy || {};

SceneBuddy = function(scene, camera) {
    this.scene = scene;
    this.camera = camera;
    this.sceneClock = new THREE.Clock();
    this.renderer = {};
    this.resolution = {};
    this.controls = {};
};
//Start Animate
SceneBuddy.prototype.startAnimate = function() {
    requestAnimationFrame(this.startAnimate); //this does not work, type error
    this.render.call(this);
};
//Render Function
SceneBuddy.prototype.render = function() {
    var delta = this.sceneClock.getDelta();
    this.controls.update(delta);
    this.renderer.render(this.scene,this.camera);
};

//Setup Renderer
SceneBuddy.prototype.initRenderer = function(resolution) {
    if (!Detector.webgl) {
        Detector.addGetWebGLMessage();
        return;
    }
    else {
        var renderer = new THREE.WebGLRenderer({
            antialias: true,
            preserveDrawingBuffer: true
        });
        renderer.setSize(resolution.x, resolution.y);
        renderer.shadowMapEnabled = true;
        this.resolution = resolution;
        this.renderer = renderer;
    }
};

我目前正在这样使用SceneBuddy:

  var camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
  var scene = new THREE.Scene();
  var sceneBuddy = new SceneBuddy(scene, camera);
  sceneBuddy.initRenderer({x: 940, y: 400});
  sceneBuddy.attachRenderer(container); //attaches renderer to dom element
  sceneBuddy.initControls();
  sceneBuddy.startAnimate(); // broken.

你是如何实例化SceneBuddy的? - bfavaretto
你能否添加完整的代码,展示如何在全局对象上设置 requestAnimationFrame 函数?另外:我希望 startAnimate 函数接受一个时间戳参数。 - Elias Van Ootegem
requestAnimationFrame是由three.js附带的shim提供的。不确定您关于提供时间戳的建议是否正确? - mhilmi
1个回答

13

当传递一个函数时,使用bind来指定函数被调用时的this:

SceneBuddy.prototype.startAnimate = function() {
    requestAnimationFrame(this.startAnimate.bind(this));
    this.render();
};

这个有效,谢谢。出于好奇,像这样的东西是必要的吗:this.render.call(this); 还是多余的?之前,除非我像上面那样调用,否则 this.render() 不起作用,一旦在渲染函数中,this 上下文就没有定义。可能只是 requestAnimationFrame 中断造成的故障。 - mhilmi
我想不出一个例子,this.render.call(this) 能够工作而 this.render() 不能 - 它们做的事情是一样的。如果你没有绑定 rAF 回调函数,那么 this 将是全局对象/窗口,它可能没有一个 render 函数。 - Dennis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接