Home > Article > Web Front-end > jQuery provides two methods for developing plug-ins
jQuery.fn.extend(); jQuery.extend();
jQuery.fn = jQuery.prototype = {init: function( selector, context ) {//….//……};
It turns out that jQuery.fn = jQuery.prototype. You will definitely be familiar with prototype. .
Although javascript does not have a clear concept of class, it is more convenient to use classes to understand it.
jQuery is a very well-encapsulated class. For example, if we use the statement $(“#btn1″), an instance of the jQuery class will be generated.
Add a class method to the jQuery class, which can be understood as adding a static method. For example:
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 Objectj Query.extend( target, object1, [objectN])
Extend an object with one or more other objects and return the extended object
var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options); //结果:settings == { validate: true, limit: 5, name: "bar" } jQuery.fn.extend(object);
Extending jQuery.prototype is to add "member functions" to the jQuery class. Instances of the jQuery class can use this "member function".
For example, we want to develop a plug-in to create 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").alertWhileClick(); // 页面上为: $("#input1") //为一个jQuery实例,当它调用成员方法 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(), and The call of jQuery.fn.extend() extends the method to the prototype of the object, so when a jQuery object is instantiated, it will have these methods. This is very important, and this is reflected everywhere in jQuery.js
jQuery.fn.extend = jQuery.prototype.extend
You can extend an object into jQuery's prototype, which is a plug-in mechanism.
(function( $ ){ $.fn.tooltip = function( options ) { }; //等价于 var tooltip = { function(options){ } }; $.fn.extend(tooltip) = $.prototype.extend(tooltip) = $.fn.tooltip })( jQuery );
The above is the detailed content of jQuery provides two methods for developing plug-ins. For more information, please follow other related articles on the PHP Chinese website!