繁体   English   中英

JavaScript上下文私有变量

[英]Javascript context private variables

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

 this._popArray, this._popObject

他们将通过访问populationArraypopulationObject变量。

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

我试图了解这是为什么,以及为什么取消注释setPopulationArray的代码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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM