JavaScript object accessing itself from within its property by its own name

Please look at below codes:

Case 1:

var a = {
    b: function(){
        console.log(a)
    },
    c:1
};

Case 2:

var a = {
    b:a,
    c:1
};

Now when I write this :

a.b() // for first
console.log(a.b) // for 2nd

I get result:

{c:1}

I have two questions:

  1. How does the property 'b' of its parent 'a' can access its parent 'a' by its name, i.e. 'a'?

  2. If it's accessing it, then why doesn't it show all the properties of 'a'?

Upvotes: 2

Views: 112

Answers (1)

taxicala
taxicala

Reputation: 21769

In your second example, you will get undefined, because at the time the object gets defined, a is undefined.

In your first example, a is created in the global scope, thats why your console.log will show the whole a object with it's functions and properties.

Upvotes: 5

Related Questions