2016-08-31 39 views
1

我已经创建了我用它来写一个全局数组,像这样一个模块:使用Javascript - 获取对象的属性值未提及

class SomeLibrary { 

    constructor(product) { 
    if (typeof window.globalArray === 'undefined'){ 
     window.globalArray = []; 
    } 
    this._someVal = 0; 
    } 
    . 
    . 
    . 
    addToGlobalArray(obj) { 
    obj.someVal = this._someVal; 
    window.globalArray.push(obj); 
    this._someVal++ 
    } 
    . 
    . 
    . 
    . 
} 

let someLib = new SomeLibrary(); 
someLib.addToGlobalArray({test: 'hello'}) 
someLib.addToGlobalArray({test: 'hello again'}); 

而且希望我的“globalArray的‘someVal’使用当前 _someVal从模块不为结果的参考的看起来像:

//I want this outcome  
[ 
    {test: 'hello', someVal: 0}, 
    {test: 'hello again', someVal: 1} 
] 

不(因为它当前操作)

//I don't want this outcome  
[ 
    {test: 'hello', someVal: 1}, //someVal here is 1 as it is a reference to the current value of _someVal in the module 
    {test: 'hello again', someVal: 1} 
] 

什么我需要做的传递值,而不是引用到全局对象?

(我没有访问的jQuery或下划线)

回答

1

你的代码已经工作你说你想要的方式。

根据定义,被添加到被添加到全局数组的对象的属性被添加的值(它在那个精确时刻的值),而不是通过引用;事实上,除了通过诸如“getters”或“proxies”这样的东西,在JS中没有办法做到这一点。

我怀疑你实际上是运行像下面的代码:

var object = {test: "hello"}; 
someLib.addToGlobalArray(object}) 

object.test = "hello again"; 
someLib.addToGlobalArray(object); 

这将导致在单个对象{test: "hello again", someVal: 1}都占据在全局阵列中的第一和第二的位置。在globalArray[0]globalArray[1]someVal具有相同值1的事实与通过引用设置它的一些概念无关;这只是因为它在两个插槽中都是相同的对象

+0

...除了{get someVal(){return self._someVal; }}' – Bergi

+0

@Bergi谢谢,解决了这个问题的答案。 –