[英]How to call a function within another function in javascript
I have created nested function in one script file A.js, like below: 我在一个脚本文件A.js中创建了嵌套函数,如下所示:
function A(){
function B(){}
}
If I want to call function B() in another script file C.js, what should I do? 如果要在另一个脚本文件C.js中调用函数B(),该怎么办?
What you want to do seems to be to create a function closure of B
using the variables within A()
. 您想要做的似乎是使用
A()
的变量创建B
的函数闭包 。 You can then access this closure B
if you return B
after you call A()
. 如果在调用
A()
之后返回B
,则可以访问此闭包B
Then, in C.js
, you can access B
by calling A
and using the return value: 然后,在
C.js
,您可以通过调用A
并使用返回值来访问B
:
A.js
: A.js
:
function A([parameters]) {
[variables]
function B() { [function body] }
//Return B from A:
return B;
}
C.js
: C.js
:
//Get B:
var bFunction = A([parameters]):
//Call bFunction:
bFunction();
You have to return the nested function: 您必须返回嵌套函数:
function A(){
return function B(){}
}
Then In C.js 然后在C.js中
var funB = A();
funB();
or 要么
A()();
You have to return the nested function B()
from the parent function A()
. 您必须从父函数
A()
返回嵌套函数B()
A()
。
Your code 您的密码
function A(){
function B(){}
}
Updated Code with return statement 使用return语句更新代码
function A(){
return function B(){ //return added
}
}
You can access the child function by adding an additional ()
Parentheses to the function call like the below example. 您可以通过向函数调用添加一个额外的
()
括号来访问子函数,如以下示例所示。
A()();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.