JavaScript上下文私有变量

时间:2018-10-15 06:55:06

标签: 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);
}

1 个答案:

答案 0 :(得分:0)

ConstraintLayout

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

请检查以下内容:

let arr = Array.apply(null, new Array(this.size)).map(e => new Lek());
arr.forEach((e, i) => getArray.call(this).push(e));

或将以下行更改为将返回this._popArray

的当前值的函数
Array.apply(null, new Array(this.size)).map(e => new Lek())
.forEach((item) => {
    this.populationArray.push(item);
});

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