简体   繁体   中英

How can I modify private variable that is returned by an objects getter?

Here is what we have:

var MyObject = function(){
    var contents = [undefined,2,undefined,4,5];

    this.getContents = function(){
       return contents;
    }
}


var o = new MyObject();

As you understand, o.getContents() has the value of [undefined,2,undefined,4,5]

What I want to do is remove the undefined values of that private array, without overwriting the entire array, without making the private contents public, and without changing the objects code in general.

return contents.filter(function(e) {return e});

filter方法在从输入数组中删除""nullundefined0值的同时创建一个新数组。

Answering my own question, that was the approach I followed:

var MyObject = function(){
    var contents = [undefined,2,undefined,4,5];

    this.getContents = function(){
       return contents;
    }
}


   // Not extending the Array prototype is always a good idea
   var reIndex = function(){
   for(var i = 0; i < this.length; i++)
   {
       //Remove this element from the array
       if(this[i] === undefined){
          this.splice(i, 1);
       }
   }

}


var o = new MyObject();

console.log(o.getContents()); //[undefined, 2, undefined, 4, 5]

reIndex.call(o.getContents());

console.log(o.getContents()); //[2, 4, 5] 

Live example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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