有没有办法建立一个关联数组,其中每个键是几个对象的哈希?我对检查每个对象的状态不感兴趣,而是检查对象的身份。
var myarray = {};
var a = new A();
var b = new B();
var c = new C();
// + is not right, but illustrates the hashing I'm after.
myarray[a + b + c] = 42;
+
运营商不对。在java中,我会为这三个实例中的每一个算术组合System.identityHashCode()
,并使用结果来创建我的新哈希键。 javascript中是否有类似的机制?
覆盖A,B和C中的.toString()
方法不是一个选项,因为我对对象标识感兴趣,而不是状态。
答案 0 :(得分:3)
实际上不可能,因为这种语言中的对象键只能是字符串,并且没有java对象标识的等价物。
:○)
答案 1 :(得分:2)
您可以覆盖原型的toString()
方法,为每个实例创建唯一的哈希值。 E.g。
A.prototype.toString = function() {
return /* something instance specific here */;
};
即使a + b + c
也适用。
更新: Afaik,您无法在JavaScript中获取实例唯一ID(无论是什么)。但是,您可以为每个实例分配一些标识符
仅当你正在创建对象时才有效。
E.g。
var addIdentityTracker = (function() {
var pad = "0000000000",
id = 1;
function generateId() {
var i = (id++).toString();
return pad.substr(0, 10 - i.length) + i;
}
return function(Constr) {
var new_constr = function() {
this.___uid = generateId();
Constr.apply(this, arguments);
};
new_constr.prototype = Constr.prototype;
new_constr.prototype.toString = function() {
return this.___uid;
};
return new_constr;
};
}());
然后执行:
A = addIdentityTracker(A);
var a = new A();
答案 2 :(得分:1)
我建议只为每个对象分配一个唯一的ID。 Javascript没有内置的唯一ID机制,但您可以为所需的任何对象分配唯一的ID,然后使用它。例如,您可以这样做:
// getUniqueID is a function that returns a unique ID for any javascript object.
// If no uniqueID is already present on the object, it coins one using a global
// counter and then stores it on the object.
// So that the uniqueID can be combined with other uniqueIDs easily and still
// create a unique union, the uniqueID here is a unique 10 character string.
// There is no randomness in the IDs as they are only required to be unique
// within the page, not random or unique in the universe. The monotomically
// increasing counter guarantees uniqueness within the page.
// Two globals we need for generating the unique ID
var idCntr = 0;
var controlStr = "0000000000"; // 10 digits long
function getUniqueID(o) {
if (!o.uniqueID) {
var base = idCntr++ + ""; // get string version of idCntr
o.uniqueID = controlStr.slice(0, controlStr.length - base.length) + base; // zero pad
}
return(o.uniqueID);
}
var myobj = {};
var a = new A();
var b = new B();
var c = new C();
myobj[getUniqueID(a) + getUniqueID(b) + getUniqueID(c)] = 42;
为了将来取回同一个对象,您必须再次以正确的顺序组合对象。如果这不容易,那么你可以确保并始终按照数字顺序将它们与最低数字组合起来,这样你总能获得一致的顺序。