--- id: 587d7db2367417b2b2512b8c challengeType: 1 forumTopicId: 301332 title: 使用 IIFE 创建一个模块 --- ## Description
一个自执行函数表达式IIFE)通常用于将相关功能分组到单个对象或者是模块中。例如,先前的挑战中定义了一个混合类: ```js function glideMixin(obj) { obj.glide = function() { console.log("Gliding on the water"); }; } function flyMixin(obj) { obj.fly = function() { console.log("Flying, wooosh!"); }; } ``` 我们可以将这些mixins分成以下模块: ```js let motionModule = (function () { return { glideMixin: function(obj) { obj.glide = function() { console.log("Gliding on the water"); }; }, flyMixin: function(obj) { obj.fly = function() { console.log("Flying, wooosh!"); }; } } })(); // 末尾的两个括号导致函数被立即调用 ``` 注意:一个自执行函数表达式IIFE)返回了一个motionModule对象。返回的这个对象包含了作为对象属性的所有mixin行为。 模块模式的优点是,所有的运动行为都可以打包成一个对象,然后由代码的其他部分使用。下面是一个使用它的例子: ```js motionModule.glideMixin(duck); duck.glide(); ```
## Instructions
创建一个名为funModule模块,将这两个mixinsisCuteMixinsingMixin包装起来。funModule应该返回一个对象。
## Tests
```yml tests: - text: funModule应该被定义并返回一个对象。 testString: assert(typeof funModule === "object"); - text: funModule.isCuteMixin应该访问一个函数。 testString: assert(typeof funModule.isCuteMixin === "function"); - text: funModule.singMixin应该访问一个函数。 testString: assert(typeof funModule.singMixin === "function"); ```
## Challenge Seed
```js let isCuteMixin = function(obj) { obj.isCute = function() { return true; }; }; let singMixin = function(obj) { obj.sing = function() { console.log("Singing to an awesome tune"); }; }; ```
## Solution
```js const funModule = (function () { return { isCuteMixin: obj => { obj.isCute = () => true; }, singMixin: obj => { obj.sing = () => console.log("Singing to an awesome tune"); } }; })(); ```