views:

130

answers:

1

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 http://stackoverflow.com/questions/1612703/how-to-design-an-object-on-singleton-pattern-in-javascript 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  A: 

I don't get an exception:

alert(A instanceof Object); // true

Tested in Chrome, IE8 and Firefox.

Greg
thanks Grey for the help ... was doing something wrong.
Ramiz Uddin
I was tyring `referenceOfA instanceof A`, where the exception was thrown. `referenceOfA instanceof Object` however returns true.
o.k.w
thanks o.k.w. Grey just realized me this.
Ramiz Uddin