0

I have a property of ArrayTest called theArray (edited to show all of ArrayTest):

function ArrayTest(theArray = []) {

let _theArray = theArray;

Object.defineProperty(this, 'theArray', {
    get: function () {
        return  _theArray;
    },
    set: function (value) {
        _theArray = value;
    }
});

this.theArray = theArray;

ArrayTest.prototype.toString = function () {
    return this.theArray + ' ';
};

} in another module, I want to use the property theArray to return an array of numbers. The property aNumber is defined such that it is equal to itself. Therefore, I would expect the output to be [1, 2, 3], but instead, all elements get the value of the last element in theArray:

let theArray = [new TheNumber(1), new TheNumber(2), new TheNumber(3)];

let aList = new ArrayTest(theArray);

console.log(aList.toString()); //[3, 3, 3] instead of [1, 2, 3].

How can I change the definition of theArray so that the above example returns [1, 2, 3]?

M4R13
  • 9
  • 1
  • 4
    You'll have to show the code for `ArrayTest` but this is almost certainly a duplicate of http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – JJJ Oct 31 '16 at 10:25
  • Most likely the flaw is in `TheNumber` which uses a global variable (similar to the `_theArray` you've shown) – Bergi Oct 31 '16 at 10:35
  • Read the answers to the other question and it makes sense. Especially the link to http://conceptf1.blogspot.se/2013/11/javascript-closures.html. But where does this code go in my example? – M4R13 Oct 31 '16 at 10:57
  • If I implement `TheNumber` like this `function TheNumber(theNumber) { this.theNumber = theNumber; TheNumber.prototype.toString = function() { return this.theNumber + ''; }}` I have `0,1,2,3` output using code you provided. Could you give complete example so the issue is reproducible? – Ivan Leonenko Oct 31 '16 at 11:26

0 Answers0