JavaScript access parent object attribute

前端 未结 6 1789
臣服心动
臣服心动 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:29

    You can use super.prop to access parent class properties. Of course, only if you are using ES6.

    0 讨论(0)
  • 2020-12-31 17:32

    Javascript is prototype based, it is not a regular OOP language like PHP or Java.

    Take a look to Inheritance and the prototype chain and implement something like Simple Javascript inheritance.

    You could probably access to parent through window.parent if it is in the global scope, but your example will not work in every case.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 17:33

    In your example you haven't inheritance. You may do this

    ...
        displayA : function(){
            console.log(parent.a);
            // 5
        },
    ...
    parent.child.parent = parent;
    parent.child.displayA();
    
    0 讨论(0)
  • 2020-12-31 17:51

    I think it doesn't really make sence to do it like that since you can access child object only through its parent. so why add a mthod displayB to the child while you can add it to the parent which has access to all child properties.

    0 讨论(0)
  • 2020-12-31 17:55

    You can use call to set the value of this:

    parent.child.displayA.call(parent); // 5
    

    You may also be interested in binding it:

    parent.child.displayA = function(){
      console.log(this.a);
    }.bind(parent);
    parent.child.displayA(); // 5
    

    Or you you can just use parent instead of this:

    parent.child.displayA = function(){
      console.log(parent.a);
    };
    parent.child.displayA(); // 5
    
    0 讨论(0)
提交回复
热议问题