Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an object property in the same object

Tags:

javascript

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?

like image 493
Akshay Khot Avatar asked Dec 27 '25 16:12

Akshay Khot


2 Answers

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
    }
}
like image 56
millerbr Avatar answered Dec 30 '25 04:12

millerbr


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());
like image 26
falsarella Avatar answered Dec 30 '25 04:12

falsarella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!