1

I'm currently using an globals object to store variables used by other objects.

globals.js

export default {
  colors: {
    bg: 0x000000,
    front: 0xffffff
  },
  scene: new THREE.scene();
};

which allow me to do this in a given class:

Foo.js

import globals from './globals.js';

class Foo {
    constructor() {
        this.color = globals.colors.front;
        // ...
        globals.scene.add(this.mesh);
    }
}

I'm wondering if this is a good way to work. Should I create a separate module for each object (say a colors.js file and a Scene.js) and import them wherever needed? Or is a globals object fine? I can't think of any drawbacks but it doesn't seem clean to me.

1 Answer 1

1

I'm learning patterns myself. This stuff does depend somewhat on your app and your particular needs.

Singleton's are often seen as an anti-pattern, but don't always have to be.

import globals from './globals.js';

class Foo {
  constructor() {
    this.color = globals.colors.front;
    // ...
    globals.scene.add(this.mesh);
  }
}

const myFoo = new Foo()

globals.colors.front.set('red')
myFoo.color.set('blue') //its the same global color

How about this?

import globals from './globals.js';

class Foo {
  constructor(color) {
    this._color = color;
    // ...
    globals.scene.add(this.mesh);
  }
}

const myFoo = new Foo(globals.colors.front)

globals.colors.front.set('red')
//myFoo._color.set('blue') //_ in name hints it's private and should not be used

This way your FOO only knows about a color that is passed. If it needs to manage and hold onto it's own color you would create an instance of THREE.Color on it, in the constructor. If it just needs to reference some color, than it could be hidden from the outside world, only caring about the reference passed to it (not caring what's in it).

Regarding the scene, you could create a manager of some kind and then whenever you ask for a new instance of Foo the manager would add it to the scene.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.