Javascript Node.js 中空函数的简写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30585420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:25:42  来源:igfitidea点击:

Shorthand for empty function in Node.js

javascriptnode.js

提问by Alexander Mills

In JS, there is shorthand for an empty object which is {}. Is there shorthand for an empty functionin JS?

在 JS 中,有一个空对象的简写,即{}. functionJS 中有空的简写吗?

The reason being, as functions are first-class objects, we use them as arguments more often, but passing in an empty function is at best ugly.

原因是,由于函数是一等对象,我们更频繁地将它们用作参数,但传入一个空函数充其量是丑陋的。

var foo = baz(function(){});

In order to declare a function, at somepoint we have to declare function(){}.

为了声明一个函数,在某个时候我们必须声明function(){}.

I would like more Node.js APIs to require a (callback) function to be passed, so the API doesn't deceivingly look synchronous. Perhaps one step in that direction would be to create shorthand for empty placeholder functions.

我希望更多的 Node.js API 需要传递一个(回调)函数,这样 API 就不会欺骗性地看起来是同步的。也许朝这个方向迈出的一步是为空的占位符函数创建速记。

回答by Bergi

No, there is not. With ES6, you might be able to use an arrow function: ()=>{}which is a bit shorter.

不,那里没有。使用 ES6,您也许可以使用箭头函数:()=>{}它有点短。

If you really need this very often (you shouldn't?!), you can declare one yourself:

如果你真的经常需要这个(你不应该?!),你可以自己声明一个:

function noop(){}

and then refer to that repeatedly. If you don't want to clutter your scope, you can also use the Function.prototypefunction (sic!) which does nothing but constantly return undefined- yet that's actually longer than your function expression.

然后反复参考。如果你不想弄乱你的范围,你也可以使用Function.prototype函数(原文如此!),它除了不断地返回之外什么都不做undefined——但这实际上比你的函数表达式长。

回答by sidonaldson

ES6 one could be:

ES6 可能是:

   const noop = () => {};

Be careful if using Babel as it doesn't transpile it correctly, instead use this:

如果使用 Babel 时要小心,因为它不能正确地转换它,而是使用这个:

   const noop = () => ({});

See this tweet as to why the curly braces are important: https://twitter.com/_ericelliott/status/601420050327711744?lang=en

请参阅此推文了解为什么大括号很重要:https: //twitter.com/_ericelliott/status/601420050327711744?lang=en

回答by Jeff Lowery

If you use lodash, there is a noop method.

如果您使用 lodash,则有一个noop 方法