我有以下插件:
(function($) {
$.fn.myPlugin = function(options) {
var opt = $.extend({}, $.fn.myPlugin.defaults, options);
if (!opt.a) {
console.log('a is required!');
return false;
}
if (!opt.b) {
console.log('b is required!');
return false;
}
if (!opt.c) {
console.log('c is required!');
return false;
}
//Rest of the logic
}
$.fn.myPlugin.defaults = {
};
});
Run Code Online (Sandbox Code Playgroud)
现在这个插件将从外部调用,如下所示:
$('div.x').myPlugin({
a:'aa',
b:'bb',
c:'cc'
});
Run Code Online (Sandbox Code Playgroud)
从插件中可以看出,我需要来自外部的a,b和c选项,即它们是强制性的.但是有10-15个强制选项和这个代码
if (!opt.a) {
console.log('a is required!');
return false;
}
if (!opt.b) {
console.log('b is required!');
return false;
}
if (!opt.c) {
console.log('c is required!');
return false;
}
Run Code Online (Sandbox Code Playgroud)
可能会变得冗长和繁琐.是否有更短或更聪明的方式来写这个?我在想一些常见的代码.
如果有那么多,你可以将它们放在一个数组中并检查:
var required = ['a', 'b', 'c'];
var index, optname;
for (index = 0; index < required.length; ++index) {
optname = required[index];
if (!(optname in opt)) {
console.log(optname + " is required");
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经走了一个if (!(optname in opt))检查那里(而不是if (!opt[optname])因为你原本有),以允许其他必须明确的选择,但对于其0,false,undefined,或其他falsey值是有效的.该in检查看到选项是否存在,而无需担心它的价值是truthy.
稍微偏离主题:您可能会选择等到失败,直到您检查了所有属性,正如@Marcus在评论中指出的那样.此外,您可能会考虑抛出异常而不是返回false,因为未能正确指定选项的人应该是异常情况......但这些都是次要的.