issue in accessing object javascript getter [duplicate]

Tag: javascript , getter , defineproperty Author: yongmei1984 Date: 2014-04-23

This question already has an answer here:

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.

What is the context of this in this code?
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.
@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?
@Barmar We are using backbone. It is controller. and it is in initialize method. So basically it is pointing to controller.
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.

Best Answer

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;

        }
    });
}