Smitha
Smitha

Reputation: 6134

Defining getters and setters in javascript

I am getting following error for the setter defined in the javascript: "RangeError: Maximum call stack size exceeded".

The code4 is as follows:

setter defn :

this.__defineSetter('_myList', function(list)  
        {
              log.debug("in setter ....");  
             if(this._myList == list)  
            {  
                 log.debug("in setter..");    
                 return;           

            }  
            this._myList = list;  
         });  

call:

myMethod = function(msg)    
{  
  try  
    {       
     this.myList = msg.myList;  
    }catch(e)
    {
        log.debug("error in calling setter... " + e);
    }  
}

I am unable to figure out why is it going to infinite loop??

Upvotes: 0

Views: 933

Answers (2)

Split Your Infinity
Split Your Infinity

Reputation: 4229

The problem is that you call the setter from within the setter...

this._myList = list;

Should create another 'private' variable to store the value. Something like this...

var _myInnerList;

this.__defineSetter__('_myList', function(list) {
  log.debug("in setter ....");  
  if(_myInnerList === list) {  
    log.debug("in setter..");    
    return;           
  }  
  _myInnerList = list;  
});  

Also use === for comparisons (always) and change __defineSetter into...

__defineSetter__

Upvotes: 1

Doug Richardson
Doug Richardson

Reputation: 10811

When you call

this._myList = list; 

it invokes the defined setter, which causes the infinite recursion.

Upvotes: 2

Related Questions