Singleton Pattern with {}?

2019-09-05 14:37发布

问题:

I apologize to move it from here as there was some confusion and thanks to Grey for answer this to realized the mistake. The topic has been moved to Javascript: Behavior of {} to discuss further.

Singleton Pattern with '{}'. Here how it is:

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

Upto here everything is clear but an object should take instanceof on it. But here if you try to use instanceof with A you got an exception.

Why?

回答1:

I don't get an exception:

alert(A instanceof Object); // true

Tested in Chrome, IE8 and Firefox.