链模式

通常情况下,通过对构造函数使用 new 会返回一个绑定到 this 上的新实例,所以我们可以在 new 出来的对象上直接用 . 访问其属性和方法。如果在普通函数中也返回当前实例,那么我们就可以使用 . 在单行代码中一次性连续调用多个方法,就好像它们被链接在一起一样,这就是 链式调用 ,又称 链模式

日常使用的 jQuery、Promise 等也使用了链模式

特点

案例

    
      /* 四边形 */
      var rectangle = {
          length: null,  // 长
          width: null,   // 宽
          color: null,   // 颜色
          
          // 这个函数是最后一步了,所以不用返回this
          getSize: function() {
              console.log(`length: ${ this.length }, width: ${ this.width }, color: ${ this.color }`)
          },
          
          /* 设置长度 */
          setLength: function(length) {
              this.length = length
              return this // 返回this
          },
          
          /* 设置宽度 */
          setWidth: function(width) {
              this.width = width
              return this  // 返回 this
          },
          
          /* 设置颜色 */
          setColor: function(color) {
              this.color = color
              return this // 返回this
          }
      }
      var rect = rectangle
        .setLength('100px')
        .setWidth('80px')
        .setColor('blue')
        .getSize()
      // 输出:length: 100px, width: 80px, color: blue
    
  

链模式不一定必须返回 this

    
      const prom1 = new Promise((resolve, reject) => {
          setTimeout(() => {
              console.log('Promise 1 resolved')
              resolve()
          }, 500)
      })
      const prom2 = prom1.then(() => {
          console.log('Then method')
      })
      console.log(prom1 === prom2)
      // 输出: false