将Threejs的IIFE函数转换为es6? [英] Converting threejs' IIFE functions to es6?

查看:130
本文介绍了将Threejs的IIFE函数转换为es6?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将我的threejs项目分解为较小的模块,但我遇到了困难.以该功能为例:

I'm trying to break my threejs project into smaller modules and I'm having a tough time. Take this function for example:

var updateCamera = (function() {
    var euler = new THREE.Euler( 0, 0, 0, 'YXZ' );

    return function() {
        euler.x = motion.rotation.x;
        euler.y = motion.rotation.y;
        camera.quaternion.setFromEuler( euler );

        camera.position.copy( motion.position );
        camera.position.y += 10.0;
    };
})();

让我们说我想将此updateCamera函数分解为自己的文件并导入.因为它是自动执行的,所以我对如何使用感到困惑.有人可以帮我吗?

Lets say I wanted to break this updateCamera function into its own file and import it. I'm a bit confused on how to since it's self executing. Can anyone give me a hand?

推荐答案

使用(默认)导出,而不是分配给(global?)updateCamera变量.您可以删除整个IIFE,因为每个模块都有自己的作用域.因此,即使在模块顶层也无法访问euler并且是静态的.

Instead of assigning to the (global?) updateCamera variable, use a (default) export. You can drop the whole IIFE, as every module has its own scope; so euler will be inaccessible and static even in the module top level.

您可能还想显式声明对Three.js的依赖,而不是依赖全局变量.

You also might want to explicitly declare the dependency on Three.js instead of relying on globals.

// updateCamera.js
import { Euler } from 'three';

var euler = new THREE.Euler( 0, 0, 0, 'YXZ' );

export default function updateCamera(camera, motion) {
    euler.x = motion.rotation.x;
    euler.y = motion.rotation.y;
    camera.quaternion.setFromEuler( euler );

    camera.position.copy( motion.position );
    camera.position.y += 10.0;
}

然后您可以在其他模块中使用它

Then you can use it in other modules by doing

// main.js
import updateCamera from './updateCamera';

…
updateCamer(camera, motion);

请注意,此处应将cameramotion作为参数传递.再说一次,不要依赖全局变量.如果您不想将它们传递到任何地方,也可以创建一个导出它们并可以从中执行的模块

Notice that camera and motion should be passed as arguments here. Again, don't depend on globals; if you don't want to pass them around everywhere you might also create a module that exports them and from which you could do

import {camera, motion} from './globals';

这篇关于将Threejs的IIFE函数转换为es6?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆