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.
Object Literal Syntax Object literals are defined using the following syntax rules: A colon separates property name[1] from value. A comma separates each name-value pair from the next. A comma after the last name-value pair is optional.
Parent object and child object in the lookup relationship are determined purely on the requirement. Example: The object which has the more number of records will be the parent object and the object which has fewer records is considered as the child object.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function.
Try referencing parentObj
directly:
var parentObj = {
attr1: 1,
attr2: 2,
childObj: {
method1: function () {
return parentObj.attr1 * parentObj.attr2;
}
}
}
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();
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();
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With