I need to call a parent property from child object

2020-01-29 04:59发布

I tried to call from child object a parent attribute

var parentObj = {  
   attr1:1,  
   attr2:2,   
   childObj:{  
      method1:function(){  
         return this.attr1 * this.attr2;  
      }  
   }  
}

but it doesn't work.

标签: javascript
5条回答
Lonely孤独者°
2楼-- · 2020-01-29 05:24

This is an another approach without referencing the parent object's name.

var parentObj = {
    attr1: 1,
    attr2: 2,
    get childObj() {
        var self = this;
        return {
            method1: function () {
                return self.attr1 * self.attr2;
            }
        }
    }
}

Can be accessed as:

parentObj.childObj.method1(); // returns 2
查看更多
Ridiculous、
3楼-- · 2020-01-29 05:39
var parentObj = {  
    attr1:1,  
    attr2:2,   
    childObj:{  
       method1:function(){  
          return this.parent.attr1 * this.parent.attr2;  
       }  
    },  
    init:function(){
       this.childObj.parent = this;
       delete this.init;
       return this;
    }  
}.init();  
查看更多
▲ chillily
4楼-- · 2020-01-29 05:42

This can be done with the power of closures!

var Construct = function() {
    var self = this;    

    this.attr1 = 1;
    this.attr2 = 2;
    this.childObj = {
        method1: function () {
            return self.attr1 * self.attr2
        }
    }
}


var obj = new Construct();
查看更多
倾城 Initia
5楼-- · 2020-01-29 05:46

Try referencing parentObj directly:

var parentObj = {  
   attr1: 1,  
   attr2: 2,   
   childObj: {  
      method1: function () {  
         return parentObj.attr1 * parentObj.attr2;  
      }  
   }  
}
查看更多
何必那么认真
6楼-- · 2020-01-29 05:48

There is a problem with referencing parent object my name because it breaks the app in case you rename it. Here is nicer approach, which I use extensively, where you pass the parent as an argument to the child init method:

var App = { 
  init: function(){    
    this.gallery.init(this);   
  },

  somevar : 'Some Var'
}

App.gallery = {
  init: function(parObj){
    this.parent = parObj;
    console.log( this.parent.somevar );  
  }

}

App.init();
查看更多
登录 后发表回答