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或下劃線)
...除了{get someVal(){return self._someVal; }}' – Bergi
@Bergi謝謝,解決了這個問題的答案。 –