myObject.myProperty = new myObject.AnotherObject ();
differ from
myObject.myProperty = new TestObject.prototype.AnotherObject ();
There is no difference. Remember that objects in JavaScript have a prototype chain. When you call new myObject.AnotherObject(); , the engine first checks for AnotherObject on myObject . Not finding it, he will check the prototype myObject , which he will find. Second version
myObject.myProperty = new TestObject.prototype.AnotherObject();
Just coming to the place where AnotherObject is AnotherObject .
TestObject.prototype.AnotherObject = function () { this.AnotherObject = new TestObject.prototype.AnotherObject(); } myObject.AnotherObject();
Just go through the code. When you say: myObject.AnotherObject(); , AnotherObject will be called, and this is myObject . The first line will try to create a new property on myObject (which is this ) by setting it to the result
new TestObject.prototype.AnotherObject();
which then re-introduces the same AnotherObject function, but this time with this sets up a new object whose prototype is installed in the prototype TestObject.prototype.AnotherObject . And so on ad infinitum
Finally,
TestObject.prototype.createAnObject = function() { this.AnotherObject = new TestObject.prototype.AnotherObject(); } myObject.createAnObject();
Will it not lead to an infinite loop, as far as I can tell, and as far as I can check: FIDDLE
Basically, createAnObject will be entered with this set to myObject . Inside which a new AnotherObject property will be created on myObject, which will be configured to a new call to the AnotherObject function which you previously configured.
Note that after making this call, the AnotherObject function will exist, but , it will be obscured by the AnotherObject that you just created. So now you can never tell
var f = new myObject.AnotherObject()
Since you now have AnotherObject property sitting right on myObject, which will be found and returned before anything is tested on the prototype.
Well, I mean, you can always say delete myObject.AnotherObject and remove this property from the object, which will then open you up to AnotherObject , which is in the prototype, but in fact you should avoid name conflicts like this to start with.
Regarding your last bit of code
A) Why not make User its own function?
B) Why not configure this.User = new ...() directly in the ClientObject constructor function? This way you will not need to check undefined C) ClientObject should be defined as
function ClientObject(){...`
you now have the impression of an implicit global.