官术网_书友最值得收藏!

Modules

Modules provide a way to encapsulate your code and create privacy. In object-oriented languages, we usually use classes for this. However, I actually believe that this is an anti-pattern rather than a good practice. Classes should be used where inheritance is desired and not just to structure your code.

I'm sure that you've encountered a lot of different module patterns in JavaScript already. One of the most popular ones that creates privacy using a function closure of an immediately invoked function expression (IIFE) is probably the revealing module pattern. If you'd like to read more about this and maybe other great patterns, I recommend the book Learning JavaScript Design Patterns, by Addy Osmani.

Within ECMAScript 6, we can now use modules to serve this purpose. We simply create one file per module, and then we use the import and export keywords to connect our modules together.

Within the ECMAScript 6 module specification, we can actually export as many things as we like from each module. We can then import these named exports from any other module. We can have one default export per module, which is especially easy to import. Default exports don't need to be named, and we don't need to know their name when importing them:

import SomeModule from './some-module.js'; 
var something = SomeModule.doSomething();
export default something;

There are many combinations on how to use modules. We will discover some of these together while working on our task management application during the upcoming chapters. If you'd like to see more examples on how to use modules, I can recommend the Mozilla Developer Network documentation (https://developer.mozilla.org) on the import and export keywords.

主站蜘蛛池模板: 郴州市| 托克逊县| 丹江口市| 新乡县| 元朗区| 赤水市| 贵定县| 大洼县| 镇雄县| 磐安县| 宁河县| 襄樊市| 图片| 永春县| 教育| 南康市| 昌都县| 龙南县| 湘潭县| 丰城市| 敦煌市| 古田县| 合阳县| 南宫市| 安西县| 子洲县| 苏州市| 竹溪县| 江华| 通渭县| 凤翔县| 巴马| 都江堰市| 普安县| 龙州县| 周口市| 娄底市| 广昌县| 平乡县| 区。| 灵宝市|