标签:
1 $(function(){ 2 $.extend({ 3 console: function(sMsg){ 4 console.log(sMsg); 5 } 6 }); 7 $.console(‘jQuery‘);// jQuery 8 });
参数类型2:传入多个对象就是对第一个对象进行扩展。
1 $(function(){ 2 var oTarget = {}; 3 4 $.extend(oTarget, {name: ‘hum‘}); 5 console.log(oTarget.name); // hum 6 7 $.extend(oTarget, {name: ‘hum‘}, {age: 20}); 8 console.log(oTarget.age); // 20 9 10 $.extend(oTarget, {name: ‘hum‘}, {name: ‘tyx‘, age: 20}); 11 console.log(oTarget.name); // tyx 同名属性会被覆盖 12 13 // 注意:$.extend()的返回值都是被扩展的对象 14 });
参数类型3:第一个参数是布尔值,后面多个对象。
如果第一个参数为true,那么会深拷贝;
如果第一个参数为false,进行的是浅拷贝(默认情况是浅拷贝),返回结果和没有布尔参数时一样,但是目标对象的值不会改变(其他情况目标对象和返回结果是同一个对象)。
1 $(function(){ 2 var oTarget = {courses: {math: 100, english: 80}}; 3 console.log($.extend(oTarget, {name: ‘hum‘, courses: { math: 50, chinese: 99}}));// {name: ‘hum‘, courses: { math: 50, chinese: 99}} 4 console.log(oTarget); // {name: ‘hum‘, courses: { math: 50, chinese: 99}} 5 6 var oTarget = {courses: {math: 100, english: 80}}; 7 console.log($.extend(false, oTarget, {name: ‘hum‘, courses: { math: 50, chinese: 99}}));// {name: ‘hum‘, courses: { math: 50, chinese: 99}} 8 console.log(oTarget); // {courses: { math: 100, english: 80}} 9 10 var oTarget = {courses: {math: 100, english: 80}}; 11 console.log($.extend(true, oTarget, {name: ‘hum‘, courses: { math: 50, chinese: 99, english: 80}}));// {name: ‘hum‘, courses: { math: 50, chinese: 99, english: 80}} 12 console.log(oTarget); // {name: ‘hum‘, courses: { math: 50, chinese: 99, english: 80}} 13 });
深拷贝和浅拷贝的区别:
深拷贝会让对象中的所有对象递归拷贝,目标对象和被拷贝对象之间不会存在任何引用关系;
浅拷贝不会让对象递归拷贝,目标对象和被拷贝对象内一层的对象类型属性相互引用。
1 $(function(){ 2 var oTarget = {courses: {math: 100, english: 80}}; 3 var oCopy = {name: ‘hum‘, courses: { math: 50, chinese: 99}}; 4 console.log($.extend(oTarget, oCopy));// {name: ‘hum‘, courses: { math: 50, chinese: 99}} 5 console.log(oTarget); // {name: ‘hum‘, courses: { math: 50, chinese: 99}} 6 console.log(oCopy.courses == oTarget.courses); // true 两个对象的courses属性指向同一个对象 7 oTarget.courses.chinese = 200; 8 console.log(oCopy.courses.chinese);// 200 9 10 var oTarget = {courses: {math: 100, english: 80}}; 11 var oCopy = {name: ‘hum‘, courses: { math: 50, chinese: 99}}; 12 console.log($.extend(true, oTarget, oCopy));// {name: ‘hum‘, courses: { math: 50, chinese: 99, english: 80}} 13 console.log(oTarget); // {name: ‘hum‘, courses: { math: 50, chinese: 99, english: 80}} 14 console.log(oCopy.courses == oTarget.courses); // false 两个对象的courses属性不再指向同一个对象 15 oTarget.courses.chinese = 200; 16 console.log(oCopy.courses.chinese);// 99 17 });
1 <div>内容</div> 2 <script src="jQuery.js"></script> 3 <script> 4 $(function(){ 5 $.fn.extend({ 6 changeColor: function(){ 7 $(this).css(‘color‘, ‘blue‘); 8 } 9 }); 10 $(‘div‘).changeColor(); 11 }); 12 </script>
标签:
原文地址:http://www.cnblogs.com/tyxloveyfq/p/4306291.html