我觉得这个jQuery无new化构建有点意思。
(function(root) {
var jQuery = function(selector, context) {
return new jQuery();
}
root.$ = root.jQuery = jQuery;
})(this);
如果使用jQuery()这种办法创建一个实例,那么它会返回new jQuery(),而由于jQuery()返回new jQuery(),那么
jQuery()=>new (new jQuery()),这就导致无限循环。。。。
jquery用一个 init 函数来代替直接 new 函数名的方式,还要考虑到 jquery 中分离作用域:
var jQuery = function(){
return new jQuery.prototype.init();
}
jQuery.prototype = {
constructor: jQuery,
init: function(){
this.jquery = 1.0;
return this;
},
jquery: 2.0,
each: function(){
console.log('each');
return this;
}
}
jQuery().jquery //1.0
jQuery.prototype.jquery //2.0
jQuery().each() // error
上面看似运行正常,但是 jQuery().each() // error
,访问不到 each 函数。实际上,new jQuery.prototype.init()
返回到是谁的实例?是 init 这个函数的实例,所以 init 函数中的 this 就没了意义。
为了访问到jQuery原型上的方法,jQuery设计了一种共享原型的设计
jQuery.prototype.init.prototype =jQuery.prototype;
这样,new jQuery.prototype.init()就可以访问到jQuery.prototype的方法了。由于
jQuery.prototype.init.prototype是一个对象,保存的是引用地址。 也不用担心循环的问题。