JavaScript轻松创建级联函数的方法示例

  

<强>一、级联函数是什么?
  

  

在一行代码上,调用一个接一个的方法。这种技术在JQuery或者其他JavaScript库中是非常常见的。
  代码如下:

        $ (' # myDiv ') .fadeOut ()。html('帅哥,你好!”).fadeIn ();      

或者:         myStr1。取代(“k”、“R”) .toUpperCase () .substr (0, 4);之前      

这种代码让我们能像阅读文字一样来阅读代码,不仅简洁,可读性强更便于维护,提高开发效率。

  

<强>那怎么用呢?
  

  

要使用级联函数,我们必须在每个函数中返回这对象(也就是后面方法中操作的对象)。现在我们开始创建个级联函数:

        var usresData=https://www.yisu.com/zixun/[   {firstName:“张”姓:“圣”,电子邮件:111 @qq.com, id: 102},   {firstName:“李”姓:“Si”,电子邮件:222 @qq.com, id: 103},   {firstName:“王”姓:“吴”,电子邮件:333 @qq.com, id: 105}   ];      函数getCaseName (str) {   返回str.replace (/\ w \ S */g函数(txt) {   返回txt.charAt (0) .toUpperCase () + txt.substr (1) .toLowerCase ();   })   }      

接下来我们定义个包含级联函数的对象:

        var用户控件={   currentUser=",   findUser=函数(userEmail) {   var arrayLength=usersData。长度,我;   (我=arrayLength - 1;我在=0;我(){   如果(usersData[我]。电子邮件===userEmail) {   这一点。currentUser=usersData[我];   打破;   }   }   返回;   },   formatName:函数(){   如果(this.currentUser) {   this.currentUser。fullName=getCaseName (this.currentUser.firstName) + " " + getCaseName (this.currentUser.lastName);   }   返回;   },   createLayout:函数(){   如果(this.currentUser) {   this.currentUser。可视数据=' https://www.yisu.com/zixun/

成员:“+ this.currentUser。fullName +‘& lt;/h3> & # 8203;   + & lt; p> ID:”+ this.currentUser。id + & lt;/p>”+“& lt; p>电子邮件:”+ this.currentUser。邮件+ & lt;/p>;   }   返回;   },   displayUser:函数(){   如果(! this.currentUser)返回;   $ (' .members-wrapper ') .append (this.currentUser.viewData);   }   }      

定义完了级联函数,我们调用的时候就会非常的优雅了:

        userController.findUser (111 @qq.com) .formatName () .createLayout () .displayUser ();      

<强>总结

  

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

JavaScript轻松创建级联函数的方法示例