开发者

Singleton Pattern with {}?

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?


I don't get an exception:

alert(A instanceof Object); // true

Tested in Chrome, IE8 and Firefox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜