zoukankan      html  css  js  c++  java
  • JavaScript 轻松创建级联函数

    级联函数是什么?

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

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

    或者:

    myStr1.replace('k', 'R').toUpperCase().substr(0,4); 
    

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

    那怎么用呢?

    要使用级联函数,我们必须在每个函数中返回 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(/wS*/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();
  • 相关阅读:
    MySQL的sql_mode合理设置
    Redis
    启动Jupyter Notebook提示ImportError: DLL load failed: 找不到指定的模块。
    Linux目录结构
    修改mysql密码报错: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
    springmvc运行原理
    博客园美化
    数据搜索
    git
    window
  • 原文地址:https://www.cnblogs.com/lvyongbo/p/6293347.html
Copyright © 2011-2022 走看看