0

I am expecting to see:
Setting

Getting

15

Can someone please explain to me why this code doesn't work? thanks

var myObj = new MyObj();
function CreateSimpleProperty(propertyName) {
    Object.defineProperty(myObj, propertyName, {
        set: function (aVal) {
            this[propertyName] = aVal;
            console.log("Setting");
        },
        get: function () {
            console.log("Getting");
            return this[propertyName];
        }
    });
}

CreateSimpleProperty("TEST");
Overlay.TEST = 15;
console.log(Overlay.TEST);
Randall Flagg
  • 4,834
  • 9
  • 33
  • 45

1 Answers1

0

Well, first, is Overlay supposed to be myObj? Assuming so, your code is going to end up in an infinite loop because this[propertyName] = aVal; in your setter is going to infinitely call the setter for itself. You will need to store that value in some other manner. Here, I've saved it to _TEST, as you can see below.

Here's the code and a working jsFiddle: http://jsfiddle.net/rgthree/3s9Kp/

var myObj = {};
function CreateSimpleProperty(propertyName) {
    Object.defineProperty(myObj, propertyName, {
        set: function (aVal) {
            this['_'+propertyName] = aVal;
            console.log("Setting");
        },
        get: function () {
            console.log("Getting");
            return this['_'+propertyName];
        }
    });
}

CreateSimpleProperty("TEST");
myObj.TEST = 15;
console.log(myObj.TEST);

(Obviously, I have no idea what your MyObj is or where Overlay comes from, so I made those fixes for the example as well).

rgthree
  • 7,217
  • 17
  • 21