修改JavaScript对象属性?
我想访问函数外部的cube.rotation。这可能吗 是的,只要修改JavaScript对象属性?,javascript,Javascript,我想访问函数外部的cube.rotation。这可能吗 是的,只要cube在范围内,就有可能。例如: function render() { requestAnimationFrame(render); renderer.render(scene, camera); // cube animation cube.rotation.x += 0.01; cube.rotation.y += 0.05; } // call render function t
cube
在范围内,就有可能。例如:
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;
如果需要全局公开多维数据集,请创建一个全局命名空间。在声明多维数据集的位置执行以下操作:
(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
然后,您可以使用以下工具访问多维数据集:
var cube = ...;
...
var NAMESPACE = window.NAMESPACE = window.NAMESPACE || {};
NAMESPACE.cube = cube;
将
名称空间
替换为名称空间的实际名称。多维数据集在哪里声明?阅读错误消息。请注意,1)在函数内部,cube
将引发引用错误,2)函数调用(render()
)返回未定义的
(或者,如果它运行的话会返回)。是-在您提供的代码中,您也不能从函数内部的访问多维数据集,因为它不存在。
window.NAMESPACE.cube.rotation.x += 0.9;