0

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.

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
Denzz
  • 1,025
  • 2
  • 11
  • 18
  • What is the context of `this` in this code? – Barmar May 09 '14 at 23:55
  • Yep, this is a variant of the loop issue. Due to hoisting `tempVar` is not local to the loop, but to the surrounding function (or global) scope. – nmaier May 09 '14 at 23:57
  • @Elclanrs : it seems that kind of issue only. but there they fixed bycreating linklistener out side of that function but in this case how can I fix it? – Denzz May 10 '14 at 00:01
  • @Barmar We are using backbone. It is controller. and it is in initialize method. So basically it is pointing to controller. – Denzz May 10 '14 at 00:02
  • What is the context is this code run in? Can you show that because `this` is the window object, if this is shown as is. – Ryan May 10 '14 at 00:33

1 Answers1

0

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;

        }
    });
}
Denzz
  • 1,025
  • 2
  • 11
  • 18