3.4 KiB
3.4 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
587d7db2367417b2b2512b8c | Use an IIFE to Create a Module | 1 |
Description
immediately invoked function expression
(IIFE
) is often used to group related functionality into a single object or module
. For example, an earlier challenge defined two mixins:
function glideMixin(obj) {We can group these
obj.glide = function() {
console.log("Gliding on the water");
};
}
function flyMixin(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
};
}
mixins
into a module as follows:
let motionModule = (function () {Note that you have an
return {
glideMixin: function(obj) {
obj.glide = function() {
console.log("Gliding on the water");
};
},
flyMixin: function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
};
}
}
})(); // The two parentheses cause the function to be immediately invoked
immediately invoked function expression
(IIFE
) that returns an object motionModule
. This returned object contains all of the mixin
behaviors as properties of the object.
The advantage of the module
pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code. Here is an example using it:
motionModule.glideMixin(duck);
duck.glide();
Instructions
module
named funModule
to wrap the two mixins
isCuteMixin
and singMixin
. funModule
should return an object.
Tests
tests:
- text: <code>funModule</code> should be defined and return an object.
testString: assert(typeof funModule === "object", '<code>funModule</code> should be defined and return an object.');
- text: <code>funModule.isCuteMixin</code> should access a function.
testString: assert(typeof funModule.isCuteMixin === "function", '<code>funModule.isCuteMixin</code> should access a function.');
- text: <code>funModule.singMixin</code> should access a function.
testString: assert(typeof funModule.singMixin === "function", '<code>funModule.singMixin</code> should access a function.');
Challenge Seed
let isCuteMixin = function(obj) {
obj.isCute = function() {
return true;
};
};
let singMixin = function(obj) {
obj.sing = function() {
console.log("Singing to an awesome tune");
};
};
Solution
const funModule = (function () {
return {
isCuteMixin: obj => {
obj.isCute = () => true;
},
singMixin: obj => {
obj.sing = () => console.log("Singing to an awesome tune");
}
};
})();