jQuery.extend()以及jQuery.isPlainObject()函数

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
 
<div id="log"></div>
<script>
$(function () { 
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
/* object2 合并到 object1 中 */
$.extend(object1, object2);
var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return "{ " +  arr.join(", ") + " }";
};
$("#log").append( printObj(object1) );// {"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
})
</script>
 
</body>

</html>

___________________________________

jQuery.isPlainObject()函数用于判断指定参数是否是一个纯粹的对象

所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的。

w( $.isPlainObject( { } ) ); // true
w( $.isPlainObject( new Object() ) ); // true
w( $.isPlainObject( { name: "CodePlayer"} ) ); // true
w( $.isPlainObject( { sayHi: function(){} } ) ); // true
w( $.isPlainObject( [ ] ) ); // false
w( $.isPlainObject( function(){ } ) ); // false
注意:
function Person(){
    this.name = "张三";
}
w( $.isPlainObject( new Person() ) ); // false
* extend(dest,src1,src2,src3...)--------直接改变dest的结构
var result=$.extend({name:"Tom",age:21},{name:"Jerry",sex:"Boy"})//{name:"Tom",age:21,sex:"Boy"}
* extend({},src1,src2,src3...)--------不改变src1的结构
var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})//{name:"Tom",age:21,sex:"Boy"}
* extend(boolean,dest,src1,src2,src3...)---------是否深拷贝
var result=$.extend( true, {}, { name: "John", location: {city: "Boston",county:"USA"} },{ last: "Resig", location: {state: "MA",county:"China"} } );
结果为:result={name:"John",last:"Resig", location:{city:"Boston",state:"MA",county:"China"}}
var result=$.extend( false, {}, { name: "John", location: {city: "Boston",county:"USA"} },{ last: "Resig", location: {state: "MA",county:"China"} } );
结果为:result={name:"John",last:"Resig",location:{state:"MA",county:"China"}}
* 省略dest参数
1$.extend(src)
该方法就是将src合并到jquery的全局对象中去,如:

$.extend({
    hello:function(){alert('hello');}
});

就是将hello方法合并到jquery的全局对象中。
2$.fn.extend(src)
该方法将src合并到jquery的实例对象中去,:

    $.fn.extend({
        hello:function(){alert('hello');}
    });


就是将hello方法合并到jquery的实例对象中。

下面例举几个常用的扩展实例:

$.extend({net:{}});


这是在jquery全局对象中扩展一个net命名空间。

$.extend($.net,{
    hello:function(){alert('hello');}
})

这是将hello方法扩展到之前扩展的Jquery的net命名空间中去。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值