Examples of how to easily create cascading functions using JavaScript and javascript
1. What are cascade functions?
Call one method after another in one line of code. This technique is very common in JQuery or other JavaScript libraries.
The Code is as follows:
Certificate ('{mydiv'{.fadeout({.html ('handsome guy, hello! '). FadeIn ();
Or:
myStr1.replace('k', 'R').toUpperCase().substr(0,4);
This type of code allows us to read the code just like reading text. It is not only concise, but also readable and easier to maintain, improving development efficiency.
How can this problem be used?
To use cascading functions, we must return this object in each function (that is, the object operated in the following method ). Now we start to create a cascade function:
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(); })}
Next we will define an object that contains cascading functions:
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. cur Invalid user. lastName) ;}return this ;}, createLayout: function () {if (this. currentUser) {this. currentUser. viewData = '
After the cascade functions are defined, we can call them very elegantly:
userController.findUser('111@qq.com').formatName().createLayout().displayUser();
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.