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?
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
}
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With