Jake Chasan
Jake Chasan

Reputation: 6550

Access Sibling Object from Function

I am trying to access an object (childObject1) which is a sibling object to the function (childObject2). Although this is the case, it appears as though the function cannot access childObject1 but it can access fields within it such as grandChildObject1.

parentObject: {
    childObject1: "Child Object 1",
    childObject2: function() {
          var grandChildObject1 = "Grandchild Object 1";
          console.log(childObject1);
          console.log(grandChildObject1)
    }
}

The first log prints:

undefined

The second log prints:

Grandchild Object 1

Why is the function not able to access the value of childObject1 if they are siblings?

Upvotes: 3

Views: 2145

Answers (3)

calingasan
calingasan

Reputation: 1005

Much like any other static methods, you would have to go though the parent object e.g. parentObject1.childObject1 when accessing it from childObject2. There is no instance of a static object hence they are not really logical siblings.

Upvotes: 0

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

You have to use this:

var parentObject = {
    childObject1: "Child Object 1",
    childObject2: function() {
          var grandChildObject1 = "Grandchild Object 1";
          console.log(this.childObject1);
          console.log(grandChildObject1);
    }
};

parentObject.childObject2();

Upvotes: 3

qiAlex
qiAlex

Reputation: 4346

You need to use this. change

console.log(childObject1);

to

console.log(this.childObject1);

Upvotes: 1

Related Questions