1.8 KiB
Raw Blame History

id, title, challengeType, forumTopicId
id title challengeType forumTopicId
587d7db2367417b2b2512b8c 使用 IIFE 创建一个模块 1 301332

--description--

一个自执行函数表达式IIFE)通常用于将相关功能分组到单个对象或者是模块中。例如,先前的挑战中定义了一个混合类:

function glideMixin(obj) {
  obj.glide = function() {
    console.log("Gliding on the water");
  };
}
function flyMixin(obj) {
  obj.fly = function() {
    console.log("Flying, wooosh!");
  };
}

我们可以将这些mixins分成以下模块:

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行为。 模块模式的优点是,所有的运动行为都可以打包成一个对象,然后由代码的其他部分使用。下面是一个使用它的例子:

motionModule.glideMixin(duck);
duck.glide();

--instructions--

创建一个名为funModule模块,将这两个mixinsisCuteMixinsingMixin包装起来。funModule应该返回一个对象。

--hints--

funModule应该被定义并返回一个对象。

assert(typeof funModule === 'object');

funModule.isCuteMixin应该访问一个函数。

assert(typeof funModule.isCuteMixin === 'function');

funModule.singMixin应该访问一个函数。

assert(typeof funModule.singMixin === 'function');

--solutions--