美文网首页前端大杂烩
JavaScript 链式调用

JavaScript 链式调用

作者: lio_zero | 来源:发表于2021-05-30 20:05 被阅读0次

本文已整理到 Github,地址 👉 blog

如果我的内容帮助到了您,欢迎点个 Star 🎉🎉🎉 鼓励鼓励 :) ~~

我希望我的内容可以帮助你。现在我专注于前端领域,但我也将分享我在有限的时间内看到和感受到的东西。


如果你使用过 JQuery,你应该会经常看到这样的操作:

$('text').css('color', 'pink').show() —— 这就是链式调用。

也就是在调用一个方法之后,还可以在该方法后面继续 .xxx() 调用其他方法,呈现链条式:

_([1, 2, 3])
  .map((n) => n * n)
  .tap(console.log)
  .thru((n) => n.reverse())
  .value()

以上是使用 Loadsh 库处理一个数组所调用的一些方法,跟 jQuery 一样都支持链式调用。下面我们来看看如何实现链式调用,其实很简单。

函数调用

在实现链式调用之前,我们先来看看一般函数的调用方式:

function F(name) {
  this.name = name
  this.sayHi = function () {
    console.log(this.name)
  }
  this.modifyName = function(name) {
    this.name = name
  }
}

const f = new F('IU')

f.sayHi() // IU
f.modifyName('UI')
f.sayHi() // UI

可以看到,我们要调用函数,需要多次重复使用一个对象变量。链式调用可以简化这样的操作。

链式调用

原理:在构造函数中创建方法时,return this 返回当前调用方法的对象,可以实现链式调用方法。

function Person(name) {
  this.name = name

  this.sayHi = function() {
    console.log(this.name)
    return this
  }

  this.modifyName = function(name) {
    this.name = name
    return this
  }
}

var person = new Person('IU')

person
  .sayHi()
  .modifyName('UI')
  .sayHi()
// IU
// UI
// Person { name: 'UI', sayHi: f, modifyName: f }

https://github.com/lgwebdream/FE-Interview/issues/22

相关文章

网友评论

    本文标题:JavaScript 链式调用

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