Object.defineProperty does not work



  • // Source.js
    Memory.sources = Memory.sources || {};
    Object.defineProperty(Source.prototype, 'memory', {
        enumerable : true,
        configurable : false,
        get: function () {
            return Memory.sources[this.id];
        },
        set: function (value) {
            Memory.sources[this.id] = value;
        }
    });
    

    but on:

    source.memory.test = 1;
    

    I have an error. What is wrong?



  • Easy, you don't have the object defined @ source.memory yet:
    try source.memory = {test:1};
    then modify your getter, so it would initialise Memory.sources[this.id] to {};



  • No! You wrong! Just try it and you understand me



  • I mean that Source.prototype.memory is exists but property memory at object is absent



  • Memory has been set
    Code



  • What you really want is

    
            Memory.sources = Memory.sources || {};
            Object.defineProperty(Source.prototype, 'memory', {
                enumerable : true,
                configurable : false,
                get: function () {
                    Memory.sources[this.id] = Memory.sources[this.id] || {};
                    return Memory.sources[this.id];
                }
            });
            var tstRoom = _.first(_.values(Game.rooms));
            var idx = 0;
            _.forEach(tstRoom.find(FIND_SOURCES), function(o){
                o.memory.idx = "I am " + idx++ + "th source";
            })
    

    result



  • This is strange, but this is work now for me without changes...
    Thank you!



  • You're welcome; Do define a setter as well, if you wish to be able to replace the whole object @ the memory index for the given source.