I have an object like this for example:
obj = {
subobj1: {
},
subobj2: {
func1: function(){
},
func2: function(){
}
},
subobj3: {
func3: function(){
},
func4: function(){
}
},
}
How do I call func1 from within func4 without having to call obj.subobj2.func1() ?
You can't exactly. You have no mean to know in what objects your function exists.
Note that it could be in more than one : you could have written this after your existing code :
var obj2 = {some:obj.subobj3};
So there can't be a unique link (and there is no accessible link) from a property value to the object holding it.
Now, supposing you'd be satisfied with a link made at object creation, you could use a factory to build your object :
obj = (function(){
var parent = {
subobj1: {
},
subobj2: {
func1: function(){
},
func2: function(){
}
},
subobj3: {
func3: function(){
},
func4: function(){
parent.subobj2.func1();
}
}
};
return parent;
})();
Then you can call
obj.subobj3.func4();
Demonstration
EDIT
I see you gave the tag OOP to your question. You should know that the pattern I gave is more frequently used to define modules. OOP in javascript is more often done using new
and prototype
, in order to enable instances sharing methods and inheritance. As you probably want modules rather than OOP, you seem to be fine, though.
See this introduction.
Here's how you can add .parent
to any sub-object with a recursive init:
var obj = {
init: function() {
for (var i in this) {
if (typeof this[i] == 'object') {
this[i].init = this.init;
this[i].init();
this[i].parent = this;
}
}
return this;
},
subobj1: {
},
subobj2: {
func1: function(){
console.log('hey');
},
func2: function(){
}
},
subobj3: {
func3: function(){
},
func4: function(){
this.parent.subobj2.func1();
}
}
}.init();
obj.subobj3.func4();
With this solution you can also use .parent
as many times as your nesting requires, like for instance if you had two levels of nesting:
this.parent.parent.subobjX.funcY();
http://jsbin.com/yuwiducadoma/1/watch?js,console
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