繁体   English   中英

我需要从对象文字中的子对象调用父属性

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

我试图从子对象中调用父属性

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

但这不起作用。

尝试直接引用parentObj

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

这可以通过关闭的力量来完成!

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

这是另一种不引用父对象名称的方法。

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

可以通过以下方式访问:

parentObj.childObj.method1(); // returns 2

引用父对象我的名字存在问题,因为如果您重命名它会破坏应用程序。 这是一种更好的方法,在我广泛使用的方法中,您将父级作为参数传递给子级init方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM