Javascript 上下文私有变量



我正在尝试创建两个私有变量。

this._popArray, this._popObject

它们将由populationArraypopulationObject变量访问。

示例:https://jsfiddle.net/3jLtqbou/2

我试图理解为什么会这样,以及为什么取消注释setPopulationArray中的代码可以修复它。

class Population{
constructor(size){
this.size = size;
this.populationArray = (() => {return getArray.call(this);})();
this.populationObject = (() => {return getObject.call(this);})();
}
initialize(){
setPopulationArray.call(this);
setPopulationObject.call(this);
}
}
// private methods
function getArray(){
// private variable of the Population class
if(this._popArray === undefined)
this._popArray = [];
return this._popArray;
}
function getObject(){
// private variable of the Population class
if(this._popObject === undefined)
this._popObject = {};
return this._popObject;
}
function setPopulationArray(){
this._popArray = Array.apply(null, new Array(this.size)).map(e => new Lek());
// the code below works as intended. I am trying to understand why the above line does not.
// let arr = Array.apply(null, new Array(this.size)).map(e => new Lek());
// arr.forEach((e, i) => getArray.call(this).push(e));
}
function setPopulationObject(){
this._popArray.forEach(element => getObject.call(this)[element.id] = element);
}
let arr = Array.apply(null, new Array(this.size)).map(e => new Lek());
arr.forEach((e, i) => getArray.call(this).push(e));

此代码有效,因为您没有创建新的 Array 对象。 populationArray 保存对第一个创建的数组的引用。

请检查类似以下内容:

Array.apply(null, new Array(this.size)).map(e => new Lek())
.forEach((item) => {
this.populationArray.push(item);
});

或将以下行更改为将返回当前值的函数 this._popArray

this.populationArray = (() => {return getArray.call(this);})();

https://jsfiddle.net/3jLtqbou/5/

最新更新