JavaScript access parent object attribute

前端 未结 6 1788
臣服心动
臣服心动 2020-12-31 17:16

I have a small issue in JS, I have two nested objects, and I would like to access a variable from the parent, like so:

var parent = {
    a : 5,

    child:          


        
6条回答
  •  囚心锁ツ
    2020-12-31 17:32

    There is no general way for the object child to know that it is a member of the parent object. In your situation, you can make a direct reference to the parent object in displayA(), like so:

    displayA : function(){
      console.log(parent.a);
    }
    

    You do not need to place parent in the global scope and use window.parent as another answer suggests; since you are declaring displayA within the scope of parent, the function will close over parent, and it will be accessible anywhere within child. Since the closure contains a reference to the parent object, you will see that changes to parent will be reflected in the behaviour of displayA. For example, suppose parent and child are defined as in your example, except displayA is modified to use parent.a. Then:

    parent.child.displayA(); //=> 5
    parent.a = 10;
    parent.child.displayA(); //=> 10
    

    All this being said, if you are trying to mimic OOP, then the other answer is right: you should read more about how the Javascript prototype chain works.

提交回复
热议问题