Ken*_* Ki 5 javascript design-patterns coding-style
问题:Javascript函数需要很少的参数来处理:
function kick(person, reason, amount) {
// kick the *person* with the *amount*, based on the *reason*
}
Run Code Online (Sandbox Code Playgroud)
由于没有办法像JS中那样在JS中执行函数重载,如果它需要设计为便于将来改进(参数添加),它可以写成:
/* Function Parameters pattern */
function kick() {
// kick the person as in *arguments[0]*, with the amount as in *arguments[1]*,
// based on the reason as in *arguments[2]*, with the strength as in *arguments[3]*
}
Run Code Online (Sandbox Code Playgroud)
要么
/* Object Configuration Pattern */
function kick(config) {
// kick the person as in *config.person*, with the amount as in *config.amount*,
// based on the reason as in *config.reason*, with the strength as in *config.strength*
}
Run Code Online (Sandbox Code Playgroud)
因此,问题是:如果我不需要使用参数增加任何属性,是否有任何重要原因使用任何一个建议的解决方案而不是另一个?
使用对象有几个优点:
考虑以下两个调用:
kick({user: u,
reason: "flood",
log: true,
rejoin: false,
timeout: 60000,
privmessage: true});
kick(u, "flood", true, false, 60000, true);
Run Code Online (Sandbox Code Playgroud)
想象一下其他人正在阅读通话内容。第一个是什么true?另请注意,几个月后您自己将处于相同的位置(不记得第四个参数是什么kick与不知道它非常相似)。
使用对象方法,您可以向函数传递一组参数,该函数必须使用这些参数来调用另一个函数
function kickgroup(users, parms) {
for (var i=0; i<users.lenght; i++) {
var uparms = Object.create(parms);
uparms.user = users[i];
kick(uparms);
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,在这种arguments情况下,您不需要使用arguments[x]语法来惩罚自己。您可以声明参数并随着函数的发展添加它们:任何尚未传递的参数都将被设置为undefined(如果需要,您仍然可以访问arguments.length以区分调用者是否显式传递了您的函数undefined)。