JQuery $.extend of usage summary

  • 2020-03-30 03:21:21
  • OfStack

JQuery provides two methods for developing plug-ins, which are:
JQuery. Fn. The extend (object);

JQuery. The extend (object);
JQuery. The extend (object); To extend the jQuery class itself. Add new methods to the class.
JQuery. Fn. The extend (object); Add methods to jQuery objects. This should make sense. Here's an example.
 
<span style="font-size:18px;"><html> 
<head> 
<title></title> 
</head> 
<body> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<script type="text/javascript" src="jquery.2.0.3.js"></script> 
<script type="text/javascript"> 
jQuery.fn.myPlugin = function(options) { 
$options = $.extend( { 
html: "no messages", 
css: { 
"color": "red", 
"font-size":"14px" 
}}, 
options); 
return $(this).css({ 
"color": $options.css.color, 

}).html($options.html); 
} 


$('.ye').myPlugin({html:"So easy,yes?",css:{"color":"green","font-size":"20px"}}); 
</script> 
</body> 
</html> 
</span> 

Okay, so you see a little bit of $.extend() up there, too.

Merge multiple objects.

This USES the ability of $.extend() to nest multiple objects.

Nesting multiple objects is a bit like merging an array.

But here is the object. For example.
 
<span style="font-size:18px;">//Usage: jQuery. The extend (obj1 obj2, obj3,..)
var Css1={size: "10px",style: "oblique"} 
var Css2={size: "12px",style: "oblique",weight: "bolder"} 
$.jQuery.extend(Css1,Css2) 
//Result: the size property of Css1 is overwritten, and the weight property of Css2 is inherited
// Css1 = {size: "12px",style: "oblique",weight: "bolder"} 
</span> 

2. Deeply nested objects.
 
<span style="font-size:18px;"> jQuery.extend( 
{ name:  " John " , location: { city:  " Boston "  } }, 
{ last:  " Resig " , location: { state:  " MA "  } } 
); 
//Results:
// => { name:  " John " , last:  " Resig " , location: { state:  " MA "  } } 
//New deeper.extend()
jQuery.extend( true, 
{ name:  " John " , location: { city:  " Boston "  } }, 
{ last:  " Resig " , location: { state:  " MA "  } } 
); 
//  The results of  
// => { name:  " John " , last:  " Resig " , 
// location: { city:  " Boston " , state:  " MA "  } } 
</span> 

3. You can add static methods to jQuery.
 
<span style="font-size:18px;"><html> 
<head> 
<title></title> 
</head> 
<body> 
<script type="text/javascript" src="jquery.2.0.3.js"></script> 
<script type="text/javascript"> 
$.extend({ 
add:function(a,b){return a+b;}, 
minus:function(a,b){return a-b}, 
multiply:function(a,b){return a*b;}, 
divide:function(a,b){return Math.floor(a/b);} 
}); 

var sum = $.add(3,5)+$.minus(3,5)+$.multiply(3,5)+$.divide(5,7); 
console.log(sum); 
</script> 
</body> 
</html></span> 

Related articles: