xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js function chain call implementation principle analysis All In One

js function chain call implementation principle analysis All In One

js 函数链式调用实现原理解析 All In One

原理剖析

jQuery 实现链式调用的原理,就是每次执行完一个方法后最后把 this 返回

demo

function Chain () {
  // ES5
}

class Chain {
  // ES6
}

const chain = new Chain();

chain
.eat()
.sleep(3)
.eat()
.sleep(6)
.work();

solutions

  1. flag version
// flag version
class Chain {
  constructor() {
    this.flag = true;
    this.time = 0;
    // EventBus, EventEmitter
    this.events = [];
  }
  eat(name = ``) {
    if(!this.flag) {
      setTimeout(() => {
        log(`eat =`, name);
      }, this.time);
    } else {
      log(`eat =`, name);
    }
    return this;
  }
  work(name = ``) {
    if(!this.flag) {
      setTimeout(() => {
        log(`work =`, name);
      }, this.time);
    } else {
      log(`work =`, name);
    }
    return this;
  }
  sleep(time = 0) {
    this.flag = false;
    this.time = 1000 * time;
    let that = this;
    setTimeout(() => {
      log(`\nsleep =`, time);
      that.flag = true;
      that.time = 0;
    }, 1000 * time);
    return that;
  }
}

const chain = new Chain();

chain
.eat('apple')
.sleep(3)
.eat('orange')
.sleep(6)
.work('programming');

场景

  1. jQuery
$(`#app`).on(`click`).

const div = $("#div");
div
.css('color: red')
.height('100px')
.width('100px');

  1. Promise
new Promise.resolve().then().then().catch().finally();

const promise = new Promise.resolve();

promise
.then()
.then()
.catch()
.finally();

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-10-19 22:43  xgqfrms  阅读(23)  评论(6编辑  收藏  举报