1

I'm trying to call this inside a nested object in an array in node.js, but it's returning undefined.

var foo = {
    dog: 'max',
    cat: {
        names: [
            { grey: this.dog }
        ]
    }

};

When I try and do foo.cat.names[0].grey it returns undefined. I'm not in any functions, so I don't believe I have to cache this, right?

Blexy
  • 9,573
  • 6
  • 42
  • 55
  • 1
    If you're not in any functions, `this` refers to the global object not the object you are constructing. Since `global.dog` doesn't exist, you're setting the `grey` property to `undefined`. – Noah Freitas Aug 28 '15 at 18:33
  • What does this have to do with node.js? –  Aug 28 '15 at 19:47

1 Answers1

2

As the others have pointed out, this doesn't exist in block scopes, only function scopes.

You will be better off defining your object in stages like this:

var foo = {};
foo.dog = 'max';
foo.cat = {
    names: [
        { grey: foo.dog }
    ]
}
galactocalypse
  • 1,905
  • 1
  • 14
  • 29