为什么jQuery要返回jQuery.fn.init对象

作者:zccst

jQuery = function( selector, context ) {

// The jQuery object is actually just the init constructor 'enhanced'

return new jQuery.fn.init( selector, context, rootjQuery );

}

 

jQuery.fn = jQuery.prototype = {

……

}

 

jQuery.fn.init.prototype = jQuery.fn;

 

在 stackoverflow 上找到类似问题:http://stackoverflow.com/questions/4754560/help-understanding-jquerys-jquery-fn-init-why-is-init-in-fn 还有这个 http://stackoverflow.com/questions/1856890/why-does-jquery-use-new-jquery-fn-init-for-creating-jquery-object-but-i-can/1858537#1858537

 

I believe the code is written in this fashion so that the new keyword is not required each time you instantiate a new jQuery object and also to delegate the logic behind the object construction to the prototype. The former I believe is to make the library cleaner to use and the latter to keep the initialisation logic cleanly in one place and allow init to be recursively called to construct and return an object that correctly matches the passed arguments.

posted @ 2014-04-22 22:10  走走停停走走  Views(381)  Comments(0Edit  收藏  举报