为什么我的数组多次返回最后一个元素而不是返回所有元素?

时间:2016-10-31 10:23:57

标签: javascript arrays

我有一个名为theArray的ArrayTest属性(编辑后显示所有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 + ' ';
};

}    在另一个模块中,我想使用属性theArray来返回一个数字数组。定义属性aNumber,使其等于自身。因此,我希望输出为[1,2,3],但所有元素都获得了阵列中最后一个元素的值:

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].

如何更改theArray的定义,以便上面的示例返回[1,2,3]?

0 个答案:

没有答案