I need to call a parent property from child object in an object literal

后端 未结 5 768
时光取名叫无心
时光取名叫无心 2020-12-02 23:16

I tried to call from child object a parent attribute

var parentObj = {  
   attr1:1,  
   attr2:2,   
   childObj:{  
      method1:function(){  
         r         


        
5条回答
  •  忘掉有多难
    2020-12-02 23:53

    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();
    

提交回复
热议问题