I didn't have a understanding on difference between intializing a variable with {} and a named-function with
new
keyword. I mean which practice should I use to give a definition of an object. Which is more appropiate and for which case?Then I made a little example to test both practices. And I found a very simple difference. Whenever you intialized an variable with
{}
, that variable is the only reference of this object definition given in{}
.{}
itself doesn't have a name so it can't be called to intialized with new. Only a reference is avaliable to get it.So it seems we can easily implement singleton pattern on objects using {}. What I see you can't have more than one instances with {} not even you can apply clone if you do you will get only a reference of that object.
Am I assuming a correct behavior of {}?
var A = {
B : 0
};
// A is an object?
document.write("A is an " + typeof A);
Lets try to clone object A
var objectOfA = new Object(A);
objectOfA.B = 1;
//Such operation is not allowed!
//var objectOfA = new A();
var referenceOfA = A;
referenceOfA.B = -1;
document.write("A.B: " + A.B);
document.write("<br/>");
The above referenceOfA.B
holds a reference of object A
, so changing the value of refer开发者_运维百科enceOfA.B
surely reflects in A.B
.
document.write("referenceOfA.B: " + referenceOfA.B);
document.write("<br/>");
If successfully cloned then objectOfA
should hold value 1
document.write("objectOfA.B: " + objectOfA.B);
document.write("<br/>");
Here are the results:
A is an object
A.B: -1
referenceOfA.B: -1
objectOfA.B: -1
This may be of use, excerpt:
CatNames.instance = null; // Will contain the one and only instance of the class
// This function ensures that I always use the same instance of the object
CatNames.getInstance = function() {
if (CatNames.instance == null) {
CatNames.instance = new CatNames();
}
return CatNames.instance;
}
Note: you should not clone singletons.
A is already an object, so new Object(A)
just returns A. You can prove this by running
var c = {};
alert(c === new Object(c));
So no cloning is going on.
What are you actually trying to do, and what does the Singleton pattern have to do with this cloning business?
For cloning objects you will have to do a bit more work. Something like below.
var a = {
val:1,
clone : function(){
return {val: a.val, clone : a.clone}
}
};
var b = a.clone();
b.val = 2;
console.log(a);
console.log(b);
Now you can clone an object and change it values. If you want to clone more complex objects, you could write a recursive function for this.
You can use these object literals as either static classes or as objects with key/value pairs.
If you want to use non static classes (sort of), use the following:
var MyClass = new function(){}
MyClass.prototype = {
val : 1
};
var a = new MyClass();
Hope this helps.
精彩评论