一、给jQuery添加静态方法
$.extend({ add:function (a,b) { return a+b; }, hello:function () { alert('hello!!!'); } }) $.hello(); //弹框hello!!! var result = $.add(1,4); console.log(result); //打印出5
二、合并对象
1、$.extend(default_obj,new_obj); 这种用法会破坏default_obj的结构,相当于默认的对象更新了。
var default_obj = { name : '张三', age : 23, hobby: ['run','swim'] }; var new_obj = { name : '李四', gender : 'man', animal:'cat' }; var result = $.extend(default_obj,new_obj); console.log(default_obj); // Object {name: "李四", age: 23, hobby: Array(2), gender: "man", animal: "cat"} console.log(new_obj); // Object {name: "李四", gender: "man", animal: "cat"} console.log(result); // Object {name: "李四", age: 23, hobby: Array(2), gender: "man", animal: "cat"}
2、$.extend({},default_obj,new_obj); 这种用法保持原来default_obj的结构。
var default_obj = { name : '张三', age : 23, hobby: ['run','swim'] }; var new_obj = { name : '李四', gender : 'man', animal:'cat' }; var result = $.extend({},default_obj,new_obj); console.log(default_obj); // Object {name: "张三", age: 23, hobby: Array(2)} console.log(new_obj); // Object {name: "李四", gender: "man", animal: "cat"} console.log(result); // Object {name: "李四", age: 23, hobby: Array(2), gender: "man", animal: "cat"}
3、$.extend(true,default_obj,new_obj); 这种用法将嵌套的子对象也进行合并,如果为false则不进行合并。
var default_obj = { name : '张三', age : 23, hobby: { key_1:'run', key_2:'swim' } }; var new_obj = { name : '李四', gender : 'man', animal:'cat', hobby: { key_1:'run', key_3:'eat' } }; var result = $.extend(true,default_obj,new_obj); console.log(default_obj); // key_1:'run' key_2:'swim' console.log(new_obj); // key_1:'run' key_3:'eat' console.log(result); // key_1:'run' key_2:'swim' key_3:'eat'