- Home /
Will this be an instance or a pointer?
Hiya all,
I'm just going to use a rough example here in pseudo code. Lets say that in Javascript I have an ObjectManager class:
class ObjectManager { // A singleton object private var anObject : MyObject = new MyObject();
// Accessor method static function getAnObject() : MyObject { return anObject; } }
Now lets say I have a class (randomClass):
class randomClass { private var randomObject : MyObject;
function Start() { anObject = ObjectManager.getAnObject(); } }
The Question: Is the variable 'randomObject' a pointer to 'anObject', or is it a copy of 'anObject'?
Answer by Ray-Pendergraph · Apr 22, 2010 at 01:32 PM
Yes that is a simple implementation of singleton. As long as the instance of anObject is never replaced in ObjectManager it will continue to hand out that particular instance. Anything you do to the instance (any state changes) outside of the ObjectManager class will in fact be done to the private instance in the ObjectManager class. They are the same. There are no pointers in JS (the term of art is reference here), but I think that is what you mean.
Also note that you can deter$$anonymous$$e if two references point to the same instance on the heap with the == operator.
refOne = Object$$anonymous$$anager.getAnObject(); refTwo = Object$$anonymous$$anager.getAnObject();
Then refOne == refTwo should be true.
The story is a little different for strings in .NET but for this it's true.
Thank-you so much ... that is exactly what I needed (and wanted) to know ;)
Answer by Lucas Meijer 1 · Apr 22, 2010 at 01:33 PM
It's a reference to anObject. You can have multiple references, all referencing a single object
Answer by Molix · Apr 22, 2010 at 03:11 PM
Important: if you want it to be a singleton you'll need to declare the variable as static. Otherwise each instance of ObjectManager will have its own anObject, which is exactly the opposite of having a single one. (Also, ObjectManager won't compile unless the variable is static because it is being referred to in the static function getAnObject().
Your answer
