巧用$.extend

$.extend 特别适合于有默认值的情况。在以下例子中,operation的name是必需的,其他项如未设置则使用默认值。

不使用$.extend的写法如下:

// this为用户设置的operation对象,如{name:"edit",title:"编辑2"}
if (!this.title) {
    if (this.name=="edit") {
        this.title="编辑";
    } else if ...
} else if (!this.icon) {
    ...
}

这种写法不仅费事,易读性也不强,难以维护。

使用$.extend,可将上述代码转换为:

// 预定义默认值
var operationDefaults = {
    edit: {title:"编辑", icon:"icon-edit"},
    ...
};
// 合并默认值和用户设置的operation对象(即代码中的this)
var operation = $.extend({}, operationDefaults[this.name], this);

这样代码就精简了很多,以后要修改默认值只需修改operationDefaults的值即可。

 

 

posted @ 2013-05-21 12:46  爱上飞飞的面码  阅读(370)  评论(0编辑  收藏  举报