2013-07-28 178 views
-1
function render() { 
    requestAnimationFrame(render); 
    renderer.render(scene, camera); 
    // cube animation 
    cube.rotation.x += 0.01; 
    cube.rotation.y += 0.05; 
} 

// call render function to render cube 

render().cube.rotation.x += 0.9; 

我想访问函数外的cube.rotation。这可能吗?修改JavaScript对象属性?

+4

立方体声明在哪里? – mohkhan

+0

阅读错误信息。注意:1)在函数内部,'cube'会引发一个ReferenceError和2)函数调用('render()')返回'undefined'(或者,如果它运行的话)。 – user2246674

+0

是的 - 在你提供的代码中,你不能从函数内部访问多维数据集,因为它不存在。 –

回答

1

是的,只要cube在范围内就可以。例如:

(function(){ 
    var cube = {rotation: {x: 0, y: 0}}; 

    function render() { 
     cube.rotation.x += 0.01; 
     cube.rotation.y += 0.05; 
    } 

    render(); 

    cube.rotation.x += 0.9; // Valid 
})(); 

cube.rotation.x += 0.9; // NOT Valid 

如果您需要全局公开多维数据集,请创建一个全局名称空间。在cube声明的地方做:

var cube = ...; 
... 
var NAMESPACE = window.NAMESPACE = window.NAMESPACE || {}; 
NAMESPACE.cube = cube; 

然后你就可以在任何地方访问使用立方体:

window.NAMESPACE.cube.rotation.x += 0.9; 

替换NAMESPACE与您的命名空间的实际名称。