一、級聯函數是什么?
在一行代碼上,調用一個接一個的方法。這種技術在 JQuery 或者其他 JavaScript 庫中是非常常見的。
代碼如下:
$('#myDiv').fadeOut().html('帥哥, 你好!').fadeIn();
或者:
myStr1.replace('k', 'R').toUpperCase().substr(0,4);
這種代碼讓我們能像閱讀文字一樣來閱讀代碼,不僅簡潔,可讀性強更便于維護,提高開發效率。
那怎么用呢?
要使用級聯函數,我們必須在每個函數中返回 this 對象(也就是后面方法中操作的對象)?,F在我們開始創建個級聯函數:
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(); })}
接下來我們定義個包含級聯函數的對象:
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); }}
定義完了級聯函數,我們調用的時候就會非常的優雅了:
userController.findUser('111@qq.com').formatName().createLayout().displayUser();
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答