2016-08-31 58 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謝謝,解決了這個問題的答案。 –