Singleton Pattern with {}?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 17:24:04

问题


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.



来源:https://stackoverflow.com/questions/1612631/singleton-pattern-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!