编写jQuery插件的方法有什么性能差异吗?

我很好奇,你可以编写一个jQuery插件的方式(性能)有什么不同,如果有的话?

我已经看过它做了几个方面:

1.使用$.extend()

 (function($){ $.fn.extend({ newPlugin: function(){ return this.each(function(){ }); } }); })(jQuery); 

2.你自己的function:

 (function($){ $.fn.newPlugin = function(){ return this.each(function(){ }); } })(jQuery); 

恕我直言,第二种方式更清洁,更容易使用,但似乎用$.extend()编写它可能有一些优势? 或者我是否过度思考这一点,没有明显的区别,这仅仅是个人偏好的问题?

(我原本以为这会被问过,但我找不到它 – 如果它在那里,请指示我)

好吧,考虑到当你执行$.extend你会调用这个方法:

 jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; 

但是当你调用$.fn.newPlugin ,你只是简单地在jQuery的原型对象上附加(或者可能覆盖)数据,这与$.fn.extend正在做的$.fn.extend ......

看起来非常明显,哪种方法的开销较小(后者)。