匿名函数表达式吗?

huangapple go评论58阅读模式
英文:

Is anonymous function expression?

问题

是匿名函数表达式吗?如果是的话,为什么不能在 JavaScript 期望表达式的任何地方使用它?

示例:

const result = String(function () {
    return 2;
});

返回的变量是什么:

'function () {\r\n    return 2;\r\n}'

但我期望以字符串格式得到 2,因为如果匿名函数是表达式,它必须作为 String 函数的参数返回 2。

我尝试在 JavaScript 期望表达式的地方使用匿名函数,但没有得到我期望的结果。

英文:

Is an anonymous function expression? if it is, why can not we use it wherever JavaScript expects an expression?

Example :

const result = String(function () {
    return 2;
});

what variable returns :

'function () {\r\n    return 2;\r\n}'

but I expected to get 2 in string format because if anonymous function is expression it must return 2 as the argument for the String function

I tried to use an anonymous function where js expects an expression but i did not get the result what i expected

答案1

得分: 2

你忘了调用这个函数。一个函数定义本身只是一个定义。如果它从未被调用,它就不会返回值。

(将函数定义解释为字符串会导致你观察到的结果,即函数的文本。)

const result = String(function () {
    return 2;
}()); // 请注意这里的额外 ()
console.log(result);
英文:

You forgot to invoke the function. A function definition by itself is just that, a definition. If it's never invoked, it won't return the value.

(And interpreting a function definition as a string results in the text of the function, which is the result you're observing.)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const result = String(function () {
    return 2;
}()); // Note the additional () here
console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月11日 00:59:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定