Pregunta

I am writing getter and setters dynamically. my code is buggy. I need help in correcting it.

Portion of my code looks like following:

var a = {};
var myArray = ["abc", "xyz", "bbb"];

for (var i = 0; i < myArray.length: i++) {
    var tempVar = myArray[i];
    Object.defineProperty(this, tempVar, {
        get: function () {
            var ret = $.extend(true, {}, a[tempVar]);
            return ret;
        },
        set: function (intObj) {
            a[intObj.type] = intObj;

        }
    });
}

The problem of mine is there in get function I want to access value of tempVar but I am not able to access it.

While defining it is not even going in get function.

And while using it is going in get function but the tempVar will be last value of array only.

If some body can guide me in this. It would be great.

¿Fue útil?

Solución

Yes that link helped. Thanks. So my code will now look like following. This is a basic concept but always run away from closures. Today learnt! Thanks.

var a = {};
var myArray = ["abc", "xyz", "bbb"];

for (var i = 0; i < myArray.length: i++) {
    var tempVar = myArray[i];
    Object.defineProperty(this, tempVar, {
        get: function (newTemp) {
           return function(){
            var ret = $.extend(true, {}, a[newTemp]);
            return ret;
           }
        }(tempVar),
        set: function (intObj) {
            a[intObj.type] = intObj;

        }
    });
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top