jQuery源码中构造对象的方法有更简单的方法么

如题所述

jQuery对象是由其prototype的init构造器进行构造实例,与prototype无关,可以抽离出来。
// 最新版本2.1.4
// 73行定义了jQuery构造函数
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
// 76行 jQuery对象通过prototype下的init方法进行构造并返回实例
return new jQuery.fn.init( selector, context );
},
// 92行 代码告诉我们 jQuery.fn 和 jQuery.prototype 是指向同一对象,也就是说fn是prototype的简写
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
// 96行修正constructor属性指回jQuery。同时jQuery对象虽然是用jQuery.fn.init方法构造,但constructor依然修正指向了jQuery,非为jQuery.fn.init,看下方代码
constructor: jQuery,
// 2735行 定义了jQuery.fn.init构造函数
init = jQuery.fn.init = function( selector, context ) {
// 2835行 使得jQuery.fn.init构造函数的原型和jQuery原型同时指向了同一个对象
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// 9202行 而$仅仅只是jQuery对象的一个别名,跟无new构造无关
window.jQuery = window.$ = jQuery;
大概的代码结构就是这样子。
jQuery仅仅为了实现无new构造,在其原型下创建了init方法(仅充当构造器)为其构造实例对象,init方法的原型和jQuery原型指向了同一个对象(当然就成了循环引用),为后续的实例方法和实例插件机制打下基础(如果不指向同一对象写实例插件将会出现$.fn.init.fn.xxxxx这一幕),并修正constructor的指向,使得看起来像是由jQuery构造器构造。
$只是jQuery对象的别名, $ === jQuery 是成立的,并且因为使用new操作符的时候 ( new jQuery() ) 和 jQuery() 的 reutrn 值会覆盖new操作符生成的实例,所以 jQuery() 和 new jQuery () 的结果也是一样的。
而题主示例是
1、 $是实现jQuery无new构造的方法
2、 $ !== jQuery
3、 jQuery() 和 new jQuery的结果是不同的
温馨提示:答案为网友推荐,仅供参考