将const和让IIFE模式不必要吗? [英] Will const and let make the IIFE pattern unnecessary?

查看:103
本文介绍了将const和让IIFE模式不必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,IIFE模式是为了ES5及以下版本没有办法创建块范围的工作。通过将所有内容包装在函数中并立即调用它,我们可以创建一个范围。



现在, let code> const 将获得更多浏览器的支持,这是否减少了对IIFE模式的需求?

解决方案

是的,只要块范围的声明(功能,块将要替换IEFE , let / const / class )被广泛采用。你需要一个范围,例如关闭?在这里你有一个块,不管它是一个循环体还是仅仅是语句列表的一部分。



然而,还有一个IEFE应用程序阻塞不能替代:模块模式。块没有返回值,并且更高范围变量的变异是丑陋的,所以我们将在创建需要私有状态的对象时看到函数表达式:

  const example =(()=> {
...
return ...;
}());


As I understand it, the IIFE pattern is a work around to the fact that ES5 and below do not have a way to create block scopes. By wrapping everything in a function and immediately invoking it, we can create a scope.

Now that let and const will gain support by more the browsers, does this reduce the need for something like the IIFE pattern?

解决方案

Yes, blocks are going to replace IEFEs, as soon as block-scoped declarations (functions, let/const/class) become widely adopted. You need a scope, e.g. for a closure? Here you have a block, be it a loop body or just part of a statement list.

However, there is still one application of IEFEs that blocks cannot replace: the module pattern. Blocks don't have return values, and mutating higher-scoped variables is ugly, so we will still see function expressions in the creation of objects that need private state:

const example = (() => {
    …
    return …;
}());

这篇关于将const和让IIFE模式不必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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