链式操作/链式调用的原理及实现

链式操作是一个挺好玩的技巧,最典型的就是jQuery的链式操作了:

$("button").click(function(){
$(this).addClass("highlight").children("a").show().end().siblings().removeClass("highlight").children("a").hide();
});

thinkphp中数据库部分也可以链式操作:

$list = Db::name('data')
->where('status', 1)
->field('id,name')
->order('id', 'desc')
->limit(10)
->select();
dump($list);

简直太方便了有木有~
链式操作的执行流程非常明确,适用于异步编程,避免线程阻塞。
其实想要自己实现链式操作也很简单,原理是在该函数执行完之后返回this,即返回该函数的执行环境,下一个函数就可以继续在这个环境下运行了。
但是,链式操作的中间函数不能有this外的其他返回值
以下给出两个简单的例子,OOP语言都可以实现链式调用
js实现过程:

//定义一个JS类
function Demo() {
  
}
//扩展它的prototype
Demo.prototype ={
    setName:function (name) {
        this.name = name;
        return this;
    },
    getName:function () {
        return this.name;
    },
    setAge:function (age) {
        this.age = age;
        return this;
    }
};
  
////工厂函数
function D() {
    return new Demo();
}
//去实现链式的调用
D().setName("CJ").setAge(18).setName();

php实现过程:

class String
{
    public $value;

    public function __construct($str=null)
    {
        $this->value = $str;
    }

    public function __call($name, $args)
    {
        $this->value = call_user_func($name, $this->value, $args[0]);
        return $this;
    }
}
$str = new String('01389');
echo $str->trim('0')->value;

2 条评论

[/0o0] [..^v^..] [0_0] [T.T] [=3-❤] [❤.❤] [^v^] [-.0] [!- -] [=x=] [→_→] [><] 更多 »
昵称
  1. 213 Google Chrome 57 Google Chrome 57 Windows 10 Windows 10

    [0_0] [T.T] [=3-❤] [=x=] [=x=] [=x=] [=x=] [=x=] [=x=] [=x=]

    1. 鸽子 鸽子 Google Chrome 57 Google Chrome 57 Windows 7 Windows 7

      嘿嘿嘿