Javascript 我需要从对象文字中的子对象调用父属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4892221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I need to call a parent property from child object in an object literal
提问by foxnet
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.
但它不起作用。
回答by Emmett
Try referencing parentObj
directly:
尝试parentObj
直接引用:
var parentObj = {
attr1: 1,
attr2: 2,
childObj: {
method1: function () {
return parentObj.attr1 * parentObj.attr2;
}
}
}
回答by Raynos
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();
回答by Mik
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();
回答by Safeer Hussain
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
回答by Banago
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:
引用父对象 my name 存在问题,因为如果您重命名它,它会破坏应用程序。这是我广泛使用的更好的方法,您可以将父方法作为参数传递给子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();