链式语法

课后整理 2020-12-10

jQuery框架最大亮点之一就是它的链式语法。实现方法:设计每一个方法的返回值都是jQuery对象(this),这样调用方法的返回结果可以为下一次调用其它方法做准备。

【示例】下面示例演示如何在函数中返回this来设计链式语法。分别为String扩展了3个方法:trim、writeln和log,其中writeln和log方法返回值都为this,而trim方法返回值为修剪后的字符串。这样就可以用链式语法在一行语句中快速调用这3个方法。

Function.prototype.method = function(name, func) {
    if(!this.prototype[name]) {
        this.prototype[name] =  func;
        return this;
    }
};
String.method('trim', function() {
    return  this.replace(/^\s+|\s+$/g, '');
});
String.method('writeln', function() {
    console.log(this); 
    return this;
});
String.method('log', function() {
    console.log(this); 
    return this;
});
var str = " abc  ";
str.trim().writeln().log();