const 和 let 会使 IIFE 模式变得不必要吗? [英] Will const and let make the IIFE pattern unnecessary?

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

问题描述

据我所知,IIFE 模式是解决 ES5 及以下无法创建块作用域这一事实的方法.通过将所有内容包装在一个函数中并立即调用它,我们可以创建一个作用域.

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.

既然 letconst 将获得更多浏览器的支持,这是否减少了对 IIFE 模式之类的需求?

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

推荐答案

是的,块将取代 IEFE,只要块作用域声明 (函数let/const/class) 被广泛采用.您需要一个范围,例如关闭?这里有一个块,无论是循环体还是语句列表的一部分.

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.

然而,IEFE 仍然有一个应用程序块无法替代:模块模式.块没有返回值,并且改变更高范围的变量是丑陋的,所以我们仍然会在需要私有状态的对象的创建中看到函数表达式:

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 和 let 会使 IIFE 模式变得不必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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