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谢谢,解决了这个问题的答案。 –