Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

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 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 referenceOfA.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...