workaround: javascript dictionary which takes objects as keys -
I read some questions and answers about javascript dictionary, but they do not meet my requirements:
- Must be able to take objects as a key
- Values should be accessible by [] - operator
So I object. Prototype The idea of overwriting "valueOf" -method in the following is as follows:
object .__ id__ = 0; Object.prototype.valueOf = function () {if (! This .__ id__) this .__ id__ = ++ Object .__ id__; Return "__id__" + this .__ id__; } Object.prototype.toString = Object.prototype.valueOf; // test var x = {p1: "5"}; Var y = [6]; Var z = {}; Z [x] = "7"; Z [y] = "8"; Console.log (z [x], z [y]);
I tested it with Google-chrome and it seems to work well, but I'm a little confused, even if it creates some drawbacks, because it's so easy to implement
Keeping this value in mind, the method is not used in the entire code for other purposes, do you think there is any harm?
This is an interesting idea, I suggest that this fulfills your first requirement but not the second I really do not have the advantage of emphasizing the use of square bracket property access notation: do you have a special requirement for it?
With jshashtable, you can assign a hashing function to Hashtable
Constructor This function has been passed to use an object as a key and it The string must return; Without touching Object.prototype
, you can use your function imbalance.
There are some disadvantages to your idea:
- Your
valueOf
method shows infor loop on any native object Will go;
- You should have a command similar to what you might want to do. Instead, all the keys will be considered unique.
- This will not work with host objects (i.e. objects provided by the environment, such as DOM elements)
Comments
Post a Comment