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(/\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();

转载于:https://www.cnblogs.com/lvyongbo/p/6293347.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值