JavaScript access parent object attribute

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

提交回复
热议问题