Javascript: Behavior Of {}
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 de
Solution 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 objectCatNames.getInstance = function() {
if (CatNames.instance == null) {
CatNames.instance = newCatNames();
}
returnCatNames.instance;
}
Note: you should not clone singletons.
Solution 2:
A is already an object, so new Object(A)
just returns A. You can prove this by running
var c = {};
alert(c === newObject(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?
Solution 3:
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:
varMyClass = newfunction(){}
MyClass.prototype = {
val : 1
};
var a = newMyClass();
Hope this helps.
Post a Comment for "Javascript: Behavior Of {}"