简体   繁体   中英

What precisely is a function value?

In JavaScript (ECMAScript 5), functions are valued (they are told to be "first-class functions").

This allows us to use them as expressions (an expression is everything which produces a value, and can contain other expressions : var exp0 = (exp1) + exp2 - exp3.function(); is a grammar-correct statement).

In the code above, there are 8 expressions : exp0, exp1, (exp1), exp2, (exp1) + exp2, exp3, exp3.function() and (exp1) + exp2 - exp3.function().


Because functions can be used as expressions, the following code is correct :

var my_function_0 = function a() {} is a named function expression.

The following code is also correct :

var my_function_1 = function() {}` is an anonymous function expression.

Both are valued, both are values.


Now, consider the code below :

function requiredIdentifier() {}

It is NOT a "named or anonymous function expression", but a function declaration.


My question is :

Does a declared function have/produce a value ?

This question is equivalent to this one : Is a declared function an expression ? (even if it's not a named or anonymous function expression ?!)

Does a declared function have/produce a value?

Yes. Regardless what syntax is used to create the function, a function is a callable object (ie it implements an internal interface that makes it callable):

function a() {}
var b = function() {}
var c = (new Function()) // or some other expression that returns a function

All of the variables a , b and c hold a function value.

The difference between the syntaxes is only when the value is created and whether/when it is bound to a variable. See var functionName = function() {} vs function functionName() {} for those details.

A function declaration is a statement, not an expression. Since statements can't be used in expressions, it's pointless to ask what its value is, since there's no way to use the value.

However, the syntax of a function declaration is identical to that of a named function expression. So if you use it anywhere that an expression is required, it will be treated as a named function expression, and the value will be the function.

For example:

(function requiredIdentifier() {})

is a parenthesis expression containing a named function expression, not a function declaration. Its value is the function that was defined.

好吧,如果您运行函数requiredIdentifier()则返回值是undefined ,而undefined实际上是javascript(ecma脚本)中的原始数据类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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