美文网首页
1.链模式

1.链模式

作者: zdxhxh | 来源:发表于2019-10-08 18:17 被阅读0次

jquery是一个典型的使用链模式调用的库,$('#test').size(),可以这样调用方法。

一、基本的链模式

传统的prototype this调用,是对象.方法()触发,然后找对象__prototo__指向的原型对象prototype.方法

链模式的思路:在prototype的方法返回this的引用,然后再次调用对象的方法

如:

function A() {}
A.prototype = { 
  a:function () { 
    console.log("明明早上还在富士山")
    return this 
  },
  b:function () { 
    console.log("转眼就到了双流机场")
    return this 
  },
  c:function () { 
    console.log("cccc")
    return this 
  },
  d:function () { 
    console.log("dddd")
    return this 
  }
}

const a = new A()
a.a().b().c().d() 
/* logs 
明明早上还在富士山
转眼就到了双流机场
cccc
dddd
*/

二、jQuery的链模式

jQuery的目的是获取DOM文档上的元素,并返回一个带有jQuery方法的对象。其中一个特点是不用new关键字创建jQuery对象。

1)、在使用new关键字创建jQuery的情况是这样的

var jQuery = function(selector) { 
  this[0] = document.getElementById(selector)
  return this 
}

我不希望在构造函数中使用DOM元素的方法,所以应该将它封装到原型对象上面。
2)、不使用new关键字创建

var jQuery = function(selector) { 
  if(this instanceof jQuery) {
    this[0] = document.getElementById(selector)
    return this 
  } else {
    return jQuery.apply({},selector)
  }
}

3)、事实上,jQuery将获取dom元素放在它的原型对象上,放在原型对象上和挂载到自己身上有什么区别?空间是一样的,区别在于实例能访问该方法。

var jQuery = function(selector) {
  return new jQuery.prototype.init(selector)
}
jQuery.prototype =  {
  init:function(selector) {
    this[0] = document.getElementById(selector)
    return this 
  },
  length:2,
  size:function() {
    return this.length
  }
}

4)、此时,init方法中的this指向一个新的对象(new 操作符setPrototypeOfinit),它的__proto__指向init的prototypeinitprototype对象为一个constructor指向init的空对象,若将initprototype替换为jQuery.prototype,此时实例对象是不是可以通过__proto__访问jQuery的实例方法。

jQuery.prototype.init.prototype = jQuery.prototype 

将原型方法定义为新的构造函数,并将原型方法的原型对象指向自身所在的原型对象,这就是jQuery的精髓所在

相关文章

网友评论

      本文标题:1.链模式

      本文链接:https://www.haomeiwen.com/subject/aoyiyctx.html