2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
id: 587d7db2367417b2b2512b8c
|
2020-12-16 00:37:30 -07:00
|
|
|
|
title: 使用 IIFE 创建一个模块
|
2018-10-10 18:03:03 -04:00
|
|
|
|
challengeType: 1
|
2020-08-04 15:15:28 +08:00
|
|
|
|
forumTopicId: 301332
|
2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --description--
|
|
|
|
|
|
|
|
|
|
一个`自执行函数表达式`(`IIFE`)通常用于将相关功能分组到单个对象或者是`模块`中。例如,先前的挑战中定义了一个混合类:
|
2020-08-04 15:15:28 +08:00
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
function glideMixin(obj) {
|
|
|
|
|
obj.glide = function() {
|
|
|
|
|
console.log("Gliding on the water");
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
function flyMixin(obj) {
|
|
|
|
|
obj.fly = function() {
|
|
|
|
|
console.log("Flying, wooosh!");
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
我们可以将这些`mixins`分成以下模块:
|
2020-08-04 15:15:28 +08:00
|
|
|
|
|
|
|
|
|
```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!");
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
})(); // 末尾的两个括号导致函数被立即调用
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
注意:一个`自执行函数表达式`(`IIFE`)返回了一个`motionModule`对象。返回的这个对象包含了作为对象属性的所有`mixin`行为。 `模块`模式的优点是,所有的运动行为都可以打包成一个对象,然后由代码的其他部分使用。下面是一个使用它的例子:
|
2020-08-04 15:15:28 +08:00
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
motionModule.glideMixin(duck);
|
|
|
|
|
duck.glide();
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
创建一个名为`funModule`的`模块`,将这两个`mixins`:`isCuteMixin`和`singMixin`包装起来。`funModule`应该返回一个对象。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
`funModule`应该被定义并返回一个对象。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
```js
|
|
|
|
|
assert(typeof funModule === 'object');
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
`funModule.isCuteMixin`应该访问一个函数。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
assert(typeof funModule.isCuteMixin === 'function');
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
`funModule.singMixin`应该访问一个函数。
|
2020-08-04 15:15:28 +08:00
|
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
assert(typeof funModule.singMixin === 'function');
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
2020-08-04 15:15:28 +08:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --solutions--
|
|
|
|
|
|