ppecher
ppecher

Reputation: 1988

Why does this variable reference not work?

this.prefixMonday[0] exists at the current scope this.prefixMonday is an array of three checkboxes this is within the initComponent method of an extend of a panel

this.weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

for(var i = 0; i<7; i++){
   this['prefix' +this.weekdays[i] +'[0]'].on('check',this.someFunction, this);
}

Firebug says it can't find: this['prefix' +this.weekdays[i] +'[0]']

Upvotes: 0

Views: 104

Answers (3)

David Ruttka
David Ruttka

Reputation: 14409

this.prefixMonday[0] is not equivalent to this['prefixMonday[0]']. It would be equivalent to this['prefixMonday'][0]. Try

for(var i = 0; i<7; i++){
   this['prefix' +this.weekdays[i]][0].on('check',this.someFunction, this);
}

Upvotes: 2

Marc B
Marc B

Reputation: 360692

this['prefix' +this.weekdays[i] +'[0]']

This would create something that looks like

this['prefixWednesday[0]']

Note that the array reference is within the string, so you're looking for a key that contains '[0]' as literal text. Are you sure you wouldn't awnt something more like:

this['prefixWednesday'][0]...

instead?

Upvotes: 1

Daff
Daff

Reputation: 44215

I'm pretty sure you have to acces

this['prefix' +this.weekdays[i]][0]

Otherwise JavaScript will search for a key with exactly the string 'prefixMonday[0]' and I don't think this is what you want. To make this more readable you might want to use a helper variable to store the name:

for(var i = 0; i<7; i++){
    var key = 'prefix' +this.weekdays[i];
    this[key][0].on('check',this.someFunction, this);
}

Upvotes: 2

Related Questions