Loupax
Loupax

Reputation: 4914

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.

Upvotes: 0

Views: 94

Answers (2)

Loupax
Loupax

Reputation: 4914

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

Upvotes: 1

sp00m
sp00m

Reputation: 48817

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

This filter methods creates a new array while removing "", null, undefined and 0 values from the input array.

Upvotes: 2

Related Questions