7

我有一个简单的类,我用它来管理three.js 中的场景。我在使用 requestAnimationFrame 循环查找函数参考时遇到问题。我知道我在这里遗漏了一些基本的东西,被困在这个噩梦中。我是否需要使用绑定或调用将 this 引用传递给 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.
4

1 回答 1

12

bind在传递函数时使用以指定this调用函数时的内容:

SceneBuddy.prototype.startAnimate = function() {
    requestAnimationFrame(this.startAnimate.bind(this));
    this.render();
};
于 2013-03-15T01:29:33.733 回答