I have something like this:
var yourNamespace = {
foo: function() {
.....
},
bar: function() {
function foobar() {....
}
}
};
Is there a possibility to call inside of foo, the foobar function inside of bar?
Tushar
87.4k21 gold badges164 silver badges182 bronze badges
asked Jul 13, 2015 at 13:38
Jakub Juszczak
8,0774 gold badges23 silver badges41 bronze badges
-
1No. The function called "foobar" is local to the function assigned to the "bar" property. Unless other code in the "bar" outer function exposes the "foobar" function somehow, then it's private and cannot be accessed from outside "bar".Pointy– Pointy2015年07月13日 13:40:45 +00:00Commented Jul 13, 2015 at 13:40
-
The short answer is no. But if you explain a little on what you're trying to achieve, we may be able to give you some good suggestions.light– light2015年07月13日 13:43:48 +00:00Commented Jul 13, 2015 at 13:43
2 Answers 2
With your exact structure you cannot however you can do something like that :
var yourNamespace = {
foo: function() {
.....
yourNamespace.foobar()
},
bar: function() {
function foobar() {....}
yourNamespace.foobar = foobar;
}
};
Or nicer, (IMO) :
var yourNamespace = {
foo: function() {
.....
yourNamespace.bar.foobar()
},
bar: function() {
yourNamespace.bar.foobar = function() {....}
}
};
Please note: in both case, bar() must run before foo() otherwise foobar is undefined
answered Jul 13, 2015 at 13:41
ben
3,5781 gold badge19 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This is just a simple Module pattern. What you should do is make bar it's own module, and return foobar from that module. Example:
var yourNamespace = {
foo: function() {
this.bar.foobar();
},
bar: {
abc: '',
foobar: function() {
console.log('do something');
}
}
};
Or you could do something more like this:
var yourNamespace = {
foo: function() {
var bar = this.bar();
},
bar: function() {
var abc = '';
function foobar() {
console.log('return abc or do something else');
return abc;
}
return {
foobar: foobar
}
}
};
Comments
lang-js