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
- 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');
场景
- jQuery
$(`#app`).on(`click`).
const div = $("#div");
div
.css('color: red')
.height('100px')
.width('100px');
- 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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16808134.html
未经授权禁止转载,违者必究!