根据 jQuery插件创作指南,基本的插件结构如下所示:
According to the jQuery plugin authoring guidelines, a basic plugin structure would look like this:
(function($){ $.fn.myPlugin = function( options ) { return this.each(function() { // Do something... }); }; })( jQuery );然而,我在我检查的几个jQuery插件中看到了以下模式:
Yet I've seen the following pattern in several jQuery plugins I've inspected:
(function($){ $.extend($.fn, { myPlugin: function( options ) { $(this).each( function() { // Do something }); }, }) })(jQuery);有人可以解释第二种方法 - 什么是 $ .extend(.. 。以及所有关于对象的符号?
Can someone explain the second approach- What is $.extend(... and the object-notation all about?
谢谢 -
推荐答案这两个基本上完成了相同的任务,但方式略有不同。
These two are basically accomplishing the same task, but in a slightly different manner.
$。fn.myPlugin = ... 直接将函数分配给jQuery名称空间中所需的位置。
$.fn.myPlugin = … is directly assigning the function to the place you want it in the jQuery namespace.
$ .extend( $ .fn,{myPlugin:... 扩展 $。fn 对象,对象指定为第二个参数在这种情况下,对象只包含一个属性 myPlugin ,这是要添加的函数。
$.extend($.fn, {myPlugin:… is extending the $.fn object with the object specified as the second parameter. In this case, the object simply contains a single property, myPlugin, which is the function to add.
你可以使用任何一种结构,虽然我个人觉得第一种结构更清洁。
You can use either structure, although I personally find the first a bit cleaner.
更多推荐
了解jQuery插件开发模式
发布评论