简体   繁体   English

如何调用嵌套在另一个函数中的函数表达式?

[英]How to call a function expression which being nested inside another function?

How to call a function expression which being nested inside another function ?如何调用嵌套在另一个函数中的函数表达式?

 let a = function() { //do something let b = function() { console.log('Hello World!') } } a();

See function expression :函数表达式

Syntax句法

var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { statements };

[...] [...]

name The function name. name函数名称。 Can be omitted, in which case the function is anonymous.可以省略,在这种情况下函数是匿名的。 The name is only local to the function body .该名称仅适用于函数体

Note the last sentence.注意最后一句话。

why should i use variable to call a function and put parentheses after it?为什么我应该使用变量来调用函数并在它后面加上括号?

You can define functions either as a function statement or as an expression.您可以将函数定义为函数语句或表达式。 See var functionName = function() {} vs function functionName() {} for more information.有关更多信息,请参阅var functionName = function() {} 与 function functionName() {}

There are different ways to define functions in Javascript like Function declaration, Function expression and Arrow functions.在 Javascript 中有多种定义函数的方法,例如函数声明、函数表达式和箭头函数。

Function declaration can be defined as follow :函数声明可以定义如下:

function a() { alert("a"); }

and you can call it by its name a()你可以用它的名字a()

and the second is function expression which can be defined in two ways:第二个是函数表达式,可以通过两种方式定义:

//Anonymous Function Expression let anotherFn = function(){}; //匿名函数表达式let anotherFn = function(){};

//Named function Expression let anotherFn = function b() {}; //命名函数表达式let anotherFn = function b() {};

you can only call the above function as anotherFn()您只能将上述函数称为anotherFn()

In anonymous function expression, the function is assigned to a variable and that function can only be called by the variable name.在匿名函数表达式中,函数被分配给一个变量,该函数只能通过变量名调用。 An anonymous function expression doesn't have any name.匿名函数表达式没有任何名称。 However, you can also provide the name to the function expression.但是,您也可以为函数表达式提供名称。 It is useful when you want to refer the current function inside the function body, eg in case of recursion.当你想在函数体内引用当前函数时,它很有用,例如在递归的情况下。 But the name is only accessible within the function body and can't be used to invoke the function outside.但该名称只能在函数体内访问,不能用于调用外部函数。 That's why you are getting error b is not defined.这就是为什么您收到错误 b 未定义的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM