Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  110] [ 1]  / answers: 1 / hits: 24823  / 12 Years ago, fri, november 23, 2012, 12:00:00

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


More From » oop

 Answers
53

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.


[#81829] Thursday, November 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
peytont

Total Points: 215
Total Questions: 110
Total Answers: 111

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;