Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.