Reputation: 4468
I have an object cats
like this:
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCat: cats[0], //error here
}
When I try to access cats[0]
, I get following error: ReferenceError: cats is not defined
If I replace cats[0]
with this.cats[0]
I get this error: Uncaught TypeError: Cannot read property '0' of undefined
Is it not possible to access an object's property within the same object? Or should I create a function inside model
and initialize currentCat
in there?
Upvotes: 3
Views: 99
Reputation: 2961
No, it's not possible. Try this instead:
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
]
}
model.currentCat = model.cats[0];
You can't use the object before it has been initialised - so, where you were trying to set currentCat
, you were still 'inside' the intialisation, and your model was not accessible.
After this code, model will look like:
model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCat: {
name: "Fossie",
url: "",
count: 0
}
}
Upvotes: 2
Reputation: 12437
You could store the current cat's index instead (and access the property in a function using this
):
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCatIndex: 0,
getCurrentCat: function() {
return this.cats[this.currentCatIndex];
}
}
console.log(model.getCurrentCat());
Upvotes: 1
Reputation: 543
Dont use it inside the model. Use it after the cats is defined.
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
// currentCat: cats[0], //error here
}
model.currentCat = model.cats[0];
Hopefully this will be good for you
Upvotes: -1