Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' is undefined inside an Object in javascript accessing property of object by another property

Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: this.Container.getElementsByTagName('input'),
        Foreign:this.Container.getElementsByTagName('input')
    }

when i ran through this code inside firebug console i get error 'this.Container' is undefined even though it is defined. How else can i access the Container property inside the Local and Foreign property. I even tried this.

Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: Container.getElementsByTagName('input'),
        Foreign:Container.getElementsByTagName('input')
    }
like image 223
Deeptechtons Avatar asked Dec 12 '25 17:12

Deeptechtons


1 Answers

You can't get this while instantiating. You can do:

Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: function(){return this.Container.getElementsByTagName('input');},
        Foreign: function(){return this.Container.getElementsByTagName('input');}
    }

And later on get Local or Foreign using Type.Local()/Type.Foreign()

or use this reduntant pattern if you need Local/Foreign within the instance:

Type= {
            Container: $get('ctl00_Main_rbtnlst_Type'),
            Local: $get('ctl00_Main_rbtnlst_Type')
                     .getElementsByTagName('input');},
            Foreign: $get('ctl00_Main_rbtnlst_Type')
                      .getElementsByTagName('input');}
        }

Or use this immediately executed function:

var Type = (function(){
   var container = $get('ctl00_Main_rbtnlst_Type'),
       local = container.getElementsByTagName('input'),
       foreign = container.getElementsByTagName('input');
   return {
           Container: container,
           Local: local,
           Foreign: foreign
          }
})();

and to be complete, you can also use a few getters, but that won't work in all browsers (especially not in IE<9)

var Type = {
    Container: $get('ctl00_Main_rbtnlst_Type'),
    get Local() {return this.Container.getElementsByTagName('input');},
    get Foreign() {return this.Container.getElementsByTagName('input');}
}

note: Local and Foreign are the same, is that what you intended?

like image 142
KooiInc Avatar answered Dec 14 '25 20:12

KooiInc