在一行代碼上,調用一個接一個的方法。這種技術在 JQuery 或者其餘 JavaScript 庫中是很是常見的。
代碼以下:html
$('#myDiv').fadeOut().html('帥哥, 你好!').fadeIn();
或者:app
myStr1.replace('k', 'R').toUpperCase().substr(0,4);
這種代碼讓咱們能像閱讀文字同樣來閱讀代碼,不只簡潔,可讀性強更便於維護,提升開發效率。函數
要使用級聯函數,咱們必須在每一個函數中返回 this 對象(也就是後面方法中操做的對象)。如今咱們開始建立個級聯函數:this
var usresData = [ {firstName: 'Zhang', lastName: 'San', email: '111@qq.com', id: 102}, {firstName: 'Li', lastName: 'Si', email: '222@qq.com', id: 103}, {firstName: 'Wang', lastName: 'Wu', email: '333@qq.com', id: 105} ]; function getCaseName(str) { return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }) }
接下來咱們定義個包含級聯函數的對象:code
var userController = { currentUser = '', findUser = function (userEmail) { var arrayLength = usersData.length, i; for (i = arrayLength - 1; i >= 0; i--) { if (usersData[i].email === userEmail) { this.currentUser = usersData[i]; break; } } return this; }, formatName: function () { if (this.currentUser) { this.currentUser.fullName = getCaseName(this.currentUser.firstName) + ' ' + getCaseName(this.currentUser.lastName); } return this; }, createLayout: function () { if (this.currentUser) { this.currentUser.viewData = '<h2>成員: ' + this.currentUser.fullName + '</h2>' + '<p>ID: ' + this.currentUser.id + '</p>' + '<p>Email: ' + this.currentUser.email + '</p>'; } return this; }, displayUser: function () { if (!this.currentUser) return; $('.members-wrapper').append(this.currentUser.viewData); } }
定義完了級聯函數,咱們調用的時候就會很是的優雅了:orm
userController.findUser('111@qq.com').formatName().createLayout().displayUser();