Reputation: 2199
I have a issue with javascript. Please take a look:
function Component(data)
{
var self = this;
self.Name = data.name;
}
function Testing() {
var self = this;
self.Components = [
{
A: new Component({
name: 'test1'
})
}, {
B: new Component({
name: 'test2'
})
}, {
C: new Component({
name: 'test3'
})
}];
}
Now what i am trying to do is, I want to access each component from Components array by its property name (A, B ,C ...). So for this i did and getting error:
var t = new Testing();
t.Components['A'].Name; ==> //Error: Cannot read property 'Name' of undefined
Whats the issue ?
Upvotes: 0
Views: 84
Reputation: 94499
To access the properties of Component
using a key self.Components
must be an object (associative array). The code attempts to access the array using a key
, which is fine for associative arrays, but will not work for a regular array as declared in the code. Switching self.Components
to an object literal will allow the properties to be accessed by key.
function Testing() {
var self = this;
self.Components = {
A: new Component({
name: 'test1'
}),
B: new Component({
name: 'test2'
}),
C: new Component({
name: 'test3'
})
};
}
JS FIDDLE: http://jsfiddle.net/fxfbe/
Upvotes: 3
Reputation: 11264
The problem is that Components
defined in the Testing
is an array, remove array and create simply as object..
function Testing() {
....
self.Components = {
A: new Component({
name: 'test1'
}),
B: new Component({
name: 'test2'
}),
C: new Component({
name: 'test3'
})
};
}
Upvotes: 1