JavaScript - Using Objects as Keys
// JavaScript - Problem with using object as key:
var a={},
b={key:'b'},
c={key:'c'};
a[b]=123;
a[c]=456;
console.log(a[b]);
The above code will log 456 instead of 123 to the console. When setting an
object property, JavaScript will implicitly stringify the parameter value. In
this case, since b and c are both objects, they will both be converted to
"[object Object]". As a result, a[b] anda[c] are both equivalent to
a["[object Object]"] and can be used interchangeably. Therefore, setting or
referencing a[c] is precisely the same as setting or referencing a[b].
JavaScript object is essentially a hashtable of name-value pairs where the
names (i.e., keys) are strings. And they are always strings. In fact, when an
object other than a string is used as a key in JavaScript, no error occurs;
rather, JavaScript silently converts it to a string and uses that value as the
key instead.
JavaScript automatically converts the key values to strings using each object’s
toString() method. And since neither foo nor bar defines its own custom
toString() method, they both use the same default implementation. That
implementation simply generates the literal string “[object Object]” when it
is invoked.
var foo = new Object();
var bar = new Object();
var map = new Object();
map[foo] = "foo"; // --> map["[Object object]"] = "foo";
map[bar] = "bar"; // --> map["[Object object]"] = "bar";
// NOTE: second mapping REPLACES first mapping!
alert(map[foo]); // --> alert(map["[Object object]"]);
// and since map["[Object object]"] = "bar",
// this will alert "bar", not "foo"!!
page revision: 1, last edited: 14 Nov 2016 09:03