0

Say I have this code:

function test() {
    this._units = {};
}
test.prototype = {
    get units() { return this._units; },
    set units(val) {
        this._units = val;

        for (var unit in this._units) {
            if (this._units[unit] === 0)
                delete this._units[unit];
        }
    }
};

Now, I can assign a unit via the following:

x = new test();
x.units['foo'] = 1;

This all works. However, when I do this,

x.units['foo'] = 0;
// x.units = { 'foo' : 0 }

It doesn't remove foo from the units as it should. How can I change this?

Thanks!

Jacob
  • 1,204
  • 1
  • 12
  • 25

1 Answers1

1

You cannot intercept when a property is created, you'd need a Proxy for that. Unfortunately, it is only a harmony draft and currently only supported in Firefox' Javascript 1.8.5.

Your setter only detects an assignment to x.units = {foo:1}, but not to x.units.foo. You could create setters for every property on the units objects that you know of, but you need an extra method to make them known in the first place (assuming you're not only assigning objects to x.units).

However, you might better not do this at all. A property that deletes itself when being set to 0 is very counterintuitive. Think of

 x.units.foo = -1; x.units.foo += 2;

Would you expect this to do the same as

 x.units.foo = -1; x.units.foo++; x.units.foo++;

? The second would yield NaN instead of 1.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164