I have a code as follow in making an object:
var myObject = {
Init: function() {
// config anything here to initiate this object.
};
}
Where myObject.Init() performs like a constructor of a class. I use this Init() to generalize the object to be initiated in a following factory pattern:
window[myObjectName].Init();
myObjectName is whatever name of the object to create.
Then again I have a 2nd choice to create an object, which is much more easier for me to actually turn the Init() into a some sort of a constructor like the code below:
var myObject = function() {
// config anything here to initiate this object.
}
With the code above, I can simply create an object like the following:
window[myObjectName]();
and practically reduces myObject code on having Init() attached to it (and every other object I would do in the factory).
However the 2nd choice comes with a disadvantage I discovered, where I can’t use this inside the object, that I actually have to explicitly use myObject to call things inside. For example:
var myObject = function() {
myObject.doSomething(); // instead of this.doSomething();
}
Which concerns me a little on variable/object reference (please correct me if I’m wrong).
Any help on these choices’ advantages and disadvantages? which do you prefer on both of these choices or can you suggest a better solution?
Thanks.
Why not use a constructor function? Both approaches that you suggested requires the object to be created and stored before it can be initialised. You can do like this:
You use the
newkeyword to create the objects:Another advantage with this is that you can use the prototype of the function to add methods to the objects that are created: