Home > Article > Web Front-end > A brief discussion on the use of $.extend() in jQuery
This article summarizes some jQuery $.extend() usage for everyone. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "jQuery Video"
Two methods for developing plug-ins with JQuery
1. jQuery.extend(object); to extend the jQuery class itself. Add new methods to the class.
2. jQuery.fn.extend(object); Add methods to jQuery objects.
jQuery.fn
jQuery.fn = jQuery.prototype = { init: function(selector, context) { //内容 } }
jQuery.fn = jQuery.prototype. O(∩_∩)O Haha~, are you familiar with this prototype? !
Although JavaScript does not have a clear concept of classes, it is more convenient to use classes to understand it. jQuery is a very well-encapsulated class. For example, if we use the statement $("#p1"), an instance of the jQuery class will be generated.
jQuery.extend(object)
Add a class to the jQuery class Method can be understood as adding a static method.
Chestnut①
jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); jQuery.min(2, 3); // 2 jQuery.max(4, 5); // 5
##jQuery.fn.extend(object);
is to add "member functions" to the jQuery class. Onlyinstances of the jQuery class can call this "member function".
Chestnut② For example, we want to develop a plug-in to make a special edit box. When it is clicked, the content in the current edit box will be alerted. You can do this:$.fn.extend({ alertWhileClick: function() { $(this).click(function() { alert($(this).val()); }); } }); //$("#input1")是jQuery的实例,调用这个扩展方法 $("#input1").alertWhileClick();The call to jQuery.extend() will not extend the method to the instance of the object. The method that refers to it also needs to be implemented through the jQuery class, such as jQuery.init()The call of jQuery.fn.extend() extends the method to the prototype of the object, so when a jQuery object is instantiated, it has these methods, which is reflected everywhere in jQuery.
JS
jQuery.fn.extend = jQuery.prototype.extend
You can extend an object into the jQuery prototype, In this case, it isplug-in mechanism.
Lizi③(function($) { $.fn.tooltip = function(options) {}; //等价于 var tooltip = { function(options) {} }; $.fn.extend(tooltip) = $.prototype.extend(tooltip) = $.fn.tooltip })(jQuery);For more programming-related knowledge, please visit:
Programming Video Course! !
The above is the detailed content of A brief discussion on the use of $.extend() in jQuery. For more information, please follow other related articles on the PHP Chinese website!