Fork me on GitHub

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();
posted @ 2017-01-17 15:38  Terry√  阅读(454)  评论(0编辑  收藏  举报