jQuery无new构建实例

我觉得这个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是一个对象,保存的是引用地址。 也不用担心循环的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值