使用命名的立即调用函数表达式(IIFE)而不是注释 [英] Using Named Immediately-Invoked Function Expression (IIFE) instead of comments

查看:146
本文介绍了使用命名的立即调用函数表达式(IIFE)而不是注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS代码中使用Named IIFE来描述和分组相关代码有什么利弊?

What are the pros and cons of utilizing Named IIFEs within JS code to describe and group related code?

我一直在使用这种模式

I've been using this "pattern" to lend structure to my more procedural code that gets executed only in one place.

(function hideStuffOnInstantiaton(){
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
}());

我认为这两个都比较适用:

// hide Stuff on Instantiaton
$('oneThing').hide().removeClass();
$('#somethign_else').slideUp();
$('.foo').fadeOut();

因为随着时间的推移,注释可能会从代码中分离出来,此评论适用于

function hideStuffOnInstantiaton(){
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
};

hideStuffOnInstantiaton();

因为如果只在一个地方执行函数, em>

becuase why separate the function and its execution if its only executed in one place?

使用此模式时是否有任何性能,可维护性,可测试性或跨浏览器注意事项?我不相信我见过很多人在野外使用这个,但我觉得它可以非常有用

Are there any performance, maintainability, testability, or cross-browser considerations when using this pattern? I don't believe I've seen many people use this in the wild butI feel as though it could be very useful

推荐答案


为什么要分离函数及其执行,如果它只在一个地方执行?

why separate the function and its execution if its only executed in one place?

在这种情况下,没有理由使用函数(带有开销) - 只是内联代码。并且不要在函数名称中隐藏注释,我认为这是一个坏的做法。如果有人从代码中分离注释,那是他的错误,而不是你的错误 - 实际上他可以包装完全不相关的东西在你的IENFE。

In that case, there's no reason to use a function (with its overhead) at all - just inline the code. And don't hide comments in function names, I'd call that a bad practise. If someone separates the comment from the code, it's his fault not yours - actually he could pack completely unrelated stuff in your IENFE as well.

虽然这种模式可能是有用的,如果你可以重复使用函数(递归)或者需要它来构建一个闭包,而命名函数使堆栈跟踪更容易调试, IE中的各种错误。所以避免它,如果你真的不需要它 - 而你不。

While this pattern could be useful if you'd reuse the function (recursively) or need it to build a closure around something, and the named function makes stacktraces easier to debug, there are various bugs in IE. So avoid it if you don't really need it - and you do not.

如果你想表达你的注释适用于一块代码,你可以明确请使用语句,并将您的注释放在其头部:

If you want to express that your comment applies to a block of code, you can explicitly use a block statement for that and put your comment at its head:

{ // hide Stuff on Instantiaton
    $('oneThing').hide().removeClass();
    $('#somethign_else').slideUp();
    $('.foo').fadeOut();
}

...虽然这很可能会让你的读者感到不必要的IEFE。

…although that'll likely confuse your readers as much as a superfluous IEFE.

这篇关于使用命名的立即调用函数表达式(IIFE)而不是注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆