1

I'm trying to pass a variable to a child object of my parent object, but its returning undefined. (clearly I'm not sure how the scoping of a JS object works).

var parent = {
    pid: '565',
    child: {
       cid: this.pid + '_child_789',
       sayHello: function(){
          alert('My id is ' + this.cid);
       }
    }
}

Calling parent.child.sayHello() logs the this.cid as undefined.

I'm (incorrectly) thinking that the child would inherit the pid property and could be referred to by this.pid, but it cannot.

Is there a way to do this without hardcoding the pid value?

I know I could do parent.child.cid = parent.pid + '_child_789' after creating the object but that is not scalable or practical for me.

jamis0n
  • 3,610
  • 8
  • 34
  • 50

1 Answers1

1

You cannot access properties like that in your object literal. I would go into more detail, however, this question has already been answered several times. Please review the following questions:

JavaScript: Access own Object Property inside Array Literal

Can a JavaScript object property refer to another property of the same object?

Community
  • 1
  • 1
Jeff Wooden
  • 5,339
  • 2
  • 19
  • 24