Reputation: 155
I am having a little trouble structuring some code in JavaScript, below is an example of how I would like to use the code:
var instance = new myObject("foo", "bar");
var sub = new myObject.subObject("x", "y", "z");
instance.doSomething();
The subObject would not have access to properties of myObject (such as "foo" and "bar", in this case), rather myObject sort of simply encapsulates subObject, if you see what I mean. In this example "x", "y" and "z" are local to the instance of myObject.subObject.
Functions within myObject, such as doSomething() may themselves create some instances of myObject.subObject, and would have access to properties of myObject, such as "foo" and "bar".
So what structural form does myObject take?
Edit:
I was thinking something along these lines:
function myObject(foo, bar) {
this.foo = foo;
this.bar = bar;
this.doSomething = function() {
var a = new this.subObject("x", "y", "z");
var b = new this.subObject("1", "2", "3");
console.log(a.x, a.y, a.z, b.x, b.y, b.z);
};
this.subObject = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
};
}
Upvotes: 0
Views: 75
Reputation: 816462
myObject.subObject
would just be a normal constructor function. There is nothing special you have to do to "islolate" properties. instance
will never know about sub
and vice versa. I'm capitalizing constructor names so that it's clearer what is an instance and what is a cosntructor:
function MyObject(a, b) {
// do stuff with a and b
}
MyObject.prototype.doSomething = function() {
var innerSub = new MyObject.SubObject();
// or
// var innerSub = new this.constructor.SubObject();
};
MyObject.SubObject = function(x, y, z)
// do stuff with x,y and z
};
var instance = new MyObject("foo", "bar");
var sub = new MyObject.SubObject("x", "y", "z");
instance.doSomething();
There really isn't anything special about MyObject.SubObject`. Since functions are objects themselves, you can just add properties to them like you want to.
Upvotes: 1
Reputation: 64933
I believe you're looking for composition.
If you've an object A
which has a B
inside, because we said has a, we're talking about an association of objects.
You might create A
and B
constructors:
var A = function() { };
var B = function(associatedA) {
this.parent = associatedA;
};
var instanceOfB = new B(new A());
// This provides access to "A" instance
var parent = instanceOfB.parent;
If you want to create instances of B
within A
, you should find no issue in there, because it's about creating an instance of A
using regular new
operator.
Upvotes: 0