Could anyone explain to me why the code sample below reports true? I would have assumed that like in C# the instance of Test1 != instance of Test2.
Update: So I think I will go with some unique identifier stored in the base of both Test1 and Test2.
function Test1() { };
function Test2() { };
var test1 = new Test1();
var test2 = new Test2();
var dict = new Array();
dict[test1] = true;
alert(dict[test2]);
Keys in ‘hashtables’ (objects, basically) are always strings. So anything you add will be converted to a string.
returns a instance of
Test1. Converted as a string, this is:The same goes for
Test2. So in fact, when storingtrueunder the key ofnew Test1()as a string, you are working with the exact same record as the one by obtaining with the keynew Test2()as a string. In other words,The actual object is therefore simply:
A solution is overwriting
.toString()like this:Then
dict[test1]will be stored asdict['Test1']anddict[test2]asdict['Test2'], which allows you to differ between them. Still, manually settingdict['Test1']would overwrite things. As far as I know, there is no way to assign an object as a key.