admin管理员组文章数量:1418411
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?
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?
Share Improve this question edited Jul 13, 2015 at 13:39 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 13, 2015 at 13:38 Jakub JuszczakJakub Juszczak 7,9174 gold badges22 silver badges41 bronze badges 2- 1 No. 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 Commented 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 Commented Jul 13, 2015 at 13:43
2 Answers
Reset to default 2With 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
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
}
}
};
本文标签: How to call a javascript function inside another functionStack Overflow
版权声明:本文标题:How to call a javascript function inside another function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745269087a2650780.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论