js-链式调用的个人理解

以前在使用js方法比如

axios({
	method:"get",
	url:"url",
	params
})
.then(res=>{
	console.log("努力减肥")
})
.catch(err=>{
	console.log("吃饭要紧")
})

使用时就很疑惑,为什么后面 . 一下就能用?
还可以选择性的只调用.catch() 或者 .then()方法
后来花了些时间自己写了个可以不停.下去的调用方式,回头百度才知道,这是链式调用。

链式调用的核心就是搞清楚后面的 . 的是什么?

那我们就用一个加减乘除案例来学习链式调用吧

function Demo(num) {		//定义demo方法体  传递参数num(初始化的参数)
  this.num = num || 0;		//初始化时如果没传递参数默认为0
  this.sum = function (num) {		//加法
    this.num += +num;
    return this;		//链式调用核心,每个方法都必须返回本身
  };
  this.minus = function (num) {		//减法
    this.num -= +num;
    return this;
  };
  this.ride = function (num) {		//乘法
    this.num *= +num;
    return this;
  };
  this.divide = function (num) {		//除法
    this.num /= +num;
    return this;
  };
  this.then = function (fn) {		//then方法,通过回调函数输出当前计算结果
    fn(this.num);
    return this;		//就算是then也要返回本身,以达到后面可以继续挂载方法
  };
}
function cLog(res){		//辅助打印方法
  console.log(res)
}

let demo = new Demo(0);		//新建一个计算实体
demo.sum(4)					//0 + 4
.then((res)=>cLog(res))		// 打印 4
.minus(2)					//4 - 2
.then((res)=>cLog(res))		// 打印 2
.divide(2)					//2 / 2
.then((res)=>cLog(res))		// 打印 1
.ride(4)					//1 * 4
.then((res)=>cLog(res))		// 打印 4

修改为class版本即

class Demo {
  constructor(num) {
    this.num = num || 0;
  }
  sum(num) {
    this.num += +num;
    return this;
  }
  minus(num) {
    this.num -= +num;
    return this;
  }
  ride(num) {
    this.num *= +num;
    return this;
  }
  divide(num) {
    this.num /= +num;
    return this;
  }
  then(fn) {
    fn(this.num);
    return this;
  }
}
let demo = new Demo(0);		//新建一个计算实体
demo.sum(4)					//0 + 4
.then((res)=>cLog(res))		// 打印 4
.minus(2)					//4 - 2
.then((res)=>cLog(res))		// 打印 2
.divide(2)					//2 / 2
.then((res)=>cLog(res))		// 打印 1
.ride(4)					//1 * 4
.then((res)=>cLog(res))		// 打印 4

如果有更漂亮的写法欢迎来讨论,让我们一起有条不紊的持续进步。
喜欢的话不妨点个小小的赞与关注,您的赞与关注将是我源源不断的前进动力。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值