微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模仿JQuery.extend函数扩展自己对象的js代码

但在写的过程中发现,如果要在之前写好的对象中添加新的静态方法或实例方法,要修改原有的对象结构,于是查看了jquery了extend方法,果然extend方法支持了jq的半边天,拿来主义,给自己的对象做扩张用。

下面进入正题:
假如有以下一个对象

var MyMath = {
//加法
Add: function(a,b){
return a + b;
},
//减法
Sub: function(a,b){
return a - b;
}
}

对象名MyMath,有两个静态方法Add和Sub,正常调用


alert(MyMath.Add(3,5)) //结果8

好,现在如果现在MyMath增加两个静态方法(乘法、除法)怎么办,并且不要修改之前写好的对象,以前我们可以这么做:

//新加一静态方法:Mul乘法
MyMath["Mul"] = function(a,b){
return a * b;
}
//新加一静态方法:Div除法
MyMath["Div"] = function(a,b){
return a / b;
}

这样,我们给MyMath添加两个方法:Mul和Div。正常调用

alert(MyMath.Add(3,5)) //结果8
alert(MyMath.Mul(3,5)) //结果15

但是,刚才增加方法的写法有点笨拙,每增加一个方法都要写一次对象名(MyMath),能不能想之前我们创建对象的时候那样,通过Json的结构去声明一个对象呢?
答案当然是可以了,通过模拟JQuery.extend函数,轻松做到。以下提取JQuery.extend函数修改函数名:

MyMath.extend = function(){
// copy reference to target object
var target = arguments[0] ||
{},i = 1,length = arguments.length,deep = false,options;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] ||
{};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !jQuery.isFunction(target))
target = {};
// extend jQuery itself if only one argument is passed
if (length == i) {
target = this;
--i;
}
for (; i < length; i++)
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null)
// Extend the base object
for (var name in options) {
var src = target[name],copy = options[name];
// Prevent never-ending loop
if (target === copy)
continue;
// Recurse if we're merging object values
if (deep && copy && typeof copy === "object" && !copy.nodeType)
target[name] = jQuery.extend(deep,// Never move original objects,clone them
src || (copy.length != null ? [] : {}),copy);
// Don't bring in undefined values
else
if (copy !== undefined)
target[name] = copy;
}
// Return the modified object
return target;
};

现在我们通过这个extend方法增加刚才我们的方法(乘法、除法):

MyMath.extend({
Mul: function(a,b){
return a * b;
},
Div: function(a,b){
return a / b;
}
});

这样的结构更加一目了然。
转载请注上来自:http://www.cnblogs.com/wbkt2t

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐