0

I'm writing classes in ES6 modules using object literals and I want to set object attributes within a function. Now I know modules are executed in strict mode by default which makes usage of this safe or at least safer, but I'm not sure whether foo() modifies the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs. Do both function calls have the same effect?

//Controller.mjs
const Controller = {
    someAttr1: [],
    someAttr2: true,

    foo: function () {
        this.someAttr1.push("some value");
        Controller.someAttr1.push("some value");
    }
};

//export Controller's interface...

//SomeOtherFile.mjs
import { Controller } from 'Controller.mjs'

Controller.foo();
Sceptical Jule
  • 889
  • 1
  • 8
  • 26

1 Answers1

1

the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs

There is only a single object in your code. The import declaration really does nothing but create an alias for the const Controller variable in the imported module. There is no second object getting instantiated.

In general, for using this vs Controller to refer to the object, see Javascript: Object Literal reference in own key's function instead of 'this'. It doesn't matter whether the code is spread across modules or not for that.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375