* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.3 KiB
2.3 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7db2367417b2b2512b8c | 使用 IIFE 创建一个模块 | 1 | 301332 | use-an-iife-to-create-a-module |
--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
的模块
,将这两个mixins
:isCuteMixin
和singMixin
包装起来。funModule
应该返回一个对象。
--hints--
funModule
应该被定义并返回一个对象。
assert(typeof funModule === 'object');
funModule.isCuteMixin
应该访问一个函数。
assert(typeof funModule.isCuteMixin === 'function');
funModule.singMixin
应该访问一个函数。
assert(typeof funModule.singMixin === 'function');
--seed--
--seed-contents--
let isCuteMixin = function(obj) {
obj.isCute = function() {
return true;
};
};
let singMixin = function(obj) {
obj.sing = function() {
console.log("Singing to an awesome tune");
};
};
--solutions--
const funModule = (function () {
return {
isCuteMixin: obj => {
obj.isCute = () => true;
},
singMixin: obj => {
obj.sing = () => console.log("Singing to an awesome tune");
}
};
})();