Hash/associative array using several objects as key

后端 未结 3 582
北海茫月
北海茫月 2021-01-27 00:59

Is there a way of making an associative array where each key is a hash of several objects? I\'m not interested in inspecting each object\'s state, but rather the object\'s ident

3条回答
  •  滥情空心
    2021-01-27 01:15

    You could overwrite the toString() method of the prototypes to create a unique hash for each instance. E.g.

    A.prototype.toString = function() {
        return /* something instance specific here */;
    };
    

    Even a + b + c would work then.

    Update: Afaik, you cannot get an instance unique id (whatever that is) in JavaScript. You could however assign each instance some identifier.

    This only works if you are creating the objects.

    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;
         };
    }());
    

    and then do:

    A = addIdentityTracker(A);
    var a = new A();
    

提交回复
热议问题