匿名 JavaScript 函数 f = > f 到底是做什么的?

我正在使用一个第三方库,它有一个以函数作为参数的函数。我正在做一些条件检查,以决定是否添加一个特定的函数作为参数,在某些情况下,我不想提供一个函数。在这种情况下提供 null 将引发错误。

我找到了这个能用的代码,但我不知道到底发生了什么。

compose(__DEV__ ? devTools() : f => f)

f => f是否等价于 () => {}是一个空的匿名函数?

26603 次浏览

f => f is similar* to function(f){ return f; }

So close, but not quite what you expected.

* - as has been pointed out in comments, there are subtle differences, but for the sake of your question, I don't think they are particularly relevant. They are very relevant in other situations.

If you want to know what f => f means, the left side is the parameter and the right side is the return value. So for example, f => f*2, is equivalent to:

function(f) {
return f * 2;
}

The code which you describe returns whatever is supplied to it as input.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

f => f is the identity function. It simply returns the argument that was passed in.

This function is often used as a default values for transformation processes, since it doesn't perform any transformation.

Is f => f equivalent to () => {} an empty anonymous function?

No. The empty function doesn't return anything. The identity function returns the passed in argument.

Others have already mentioned what f => f does, so I'm not going to go deeper into that. I'm just going to explain the rest of the function, because there's a bit of a difference between f => f and __DEV__ ? devTools() : f => f

The ternary operator checks if __DEV__ is a truthy value, and if so, it return function devTools(). otherwise, it return the identity function f => f which does nothing. Put differently: this code enables some development mode functions. Without the remaining code, it's hard to tell what this mode adds, but presumably, it will enable some extra logging information and less obfuscation.

Anytime with the similar dilemma, you can use Babel to get the answer.

It returned like this:

"use strict";


(function (f) {
return f;
});

BTW, => you used is ES6 feature called arrow expression. The other expression of interest

() => {};  // es6

would convert to:

(function () {});

Since arrow function expressions are always anonymous it makes sense if you add the name to the function:

let empty = () => {}; // es6

would convert to

var empty = function empty() {};