0

I have a Javascript object nested within another object like so:

function Outer() {
    this.outerProp;
    this.inner = new function() {
        this.innerProp;
    }
}

I need to create a method to initialize the inner object. I could nest the init method inside the inner object, or I could place it outside the scope of the inner object:

var outer = new Outer();
outer.inner.init();  // Option 1
outer.initInner();  //Option 2

Would one of these options be preferred over the other? I'm leaning toward Option 1 so that I can bundle all of the data and methods related to outer.inner together. Is there any reason not to do it this way?

Matt
  • 273
  • 1
  • 2
  • 10

1 Answers1

0

I'm leaning toward Option 1 so that I can bundle all of the data and methods related to outer.inner together.

Yes. Encapsulation is exactly the reason to do it this way, instead of having some unrelated method on outer. You even might want to take the inner constructor out of the outer part and only call it from there.

… = new function() { … }

Do not use this pattern. Use an object literal or a plain IEFE instead.

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