JavaScript 调用嵌套函数
我有以下代码:
function initValidation()
{
// irrelevant code here
function validate(_block){
// code here
}
}
有什么方法可以在 initValidation()
函数之外调用 validate()
函数吗?我尝试过调用 validate()
但我认为它仅在父函数中可见。
I have the following piece of code:
function initValidation()
{
// irrelevant code here
function validate(_block){
// code here
}
}
Is there any way I can call the validate()
function outside the initValidation()
function? I've tried calling validate()
but I think it's only visible inside the parent function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
希望您正在寻找这样的东西,
这会起作用。
希望这能解决您的问题。
Hope that you are looking for something like this
This will work.
Hope this addresses your problem.
您可以从
initValidation
中调用validate
。像这样。validate
对于initValidation
之外的任何内容都是不可见的,因为它的 范围。编辑:这是我的解决方案建议。
您的所有函数都将对函数包装器之外的任何内容隐藏,但都可以互相看到。
You can call
validate
from withininitValidation
. Like this.validate
is not visible to anything outside ofinitValidation
because of its scope.Edit: Here's my suggestion of a solution.
All of your functions will be hidden to anything outside the function wrapper but can all see each other.
该调用将返回函数语句,即函数验证。
所以你可以在第一次调用后直接调用。
This invocation will return function statement, which is function validate.
So you can invoke directly after the first invocation.
我知道这是一篇旧文章,但如果您希望创建一组您希望使用的实例来重用代码,您可以执行以下操作:
I know this is an old post but if you wish to create a set of instances that you wish to work with that reuse the code you could do something like this:
我知道这个线程已经存在很长一段时间了,但我想我也应该留下 0.02$ 来讨论如何从其范围之外调用内部函数(可能会让某人受益)。
请注意,在任何地方,都应该考虑更好的设计决策,而不是一些会在以后给您带来麻烦的黑客解决方案。
如何使用 函数表达式 而不是 < a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_declaration_(function_statement)" rel="nofollow noreferrer">函数语句并利用全局范围。
或者,您可以使用闭包 :
I know this thread's been here for quite some time but I thought I'd also leave my 0.02$ on how to call inner functions from outside their scope (might benefit somebody).
Note that in any place, a better design decision should be taken into consideration rather than some hackish workaround which will bite you back later.
How about using function expressions instead of function statements and making use of the global scope.
Or, you can make use of closures:
在父函数外部创建一个变量,然后在父函数中将所需的函数存储在该变量中。
Create a variable outside the parent function, then in the parent function store your required function in the variable.
作为 Esailija 答案的一个微小变化,我这样做了:
所以 validate() 现在在 createTree() 和 addNodes() 之间完美共享,并且对外界完全不可见。
As a minor variation of Esailija's answer, I did this:
so validate() is now perfectly shared between createTree() and addNodes(), and perfectly invisible to the outside world.
函数定义:
调用如下:
Function definition:
Call it as below:
应该有效。
Should work.