如何将javascript对象值传递给其“子”对象

时间:2014-04-24 01:50:44

标签: javascript inheritance javascript-objects

我试图将变量传递给父对象的子对象,但是它返回未定义。 (很明显,我不确定JS对象的作用域是如何工作的。)

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

调用parent.child.sayHello()会将this.cid记录为未定义。

我(错误地)认为孩子会继承pid属性并且可以被this.pid引用,但它不能。

有没有办法在不对pid值进行硬编码的情况下执行此操作?

我知道在创建对象后我可以parent.child.cid = parent.pid + '_child_789'但这对我来说不具有可扩展性或实用性。

1 个答案:

答案 0 :(得分:1)

您无法在对象文字中访问此类属性。我会详细介绍,然而,这个问题已经多次回答了。请查看以下问题:

JavaScript: Access own Object Property inside Array Literal

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