在搬磚的過程中,可能會遇到很多的鏈式調用,最常見的那就是jquery中鏈式調用,如下圖:
$("p").css("color","red").height("100px");
那麼問題來了,它是怎麼實現的呢?
原理
首先咱們先用js來模擬一下這個效果:
class Person {
constructor(name) {
this.name = name;
}
eat() {
console.log(this.name + '正在喫飯');
return this;
}
drink() {
console.log(this.name + '正在喝水');
return this;
}
end() {
console.log(this.name + '測試完畢');
return this;
}
}
var p = new Person("果果");
p.eat().drink().end();
現在,咱們仔細觀察一下,這個類,其實就是每一個方法的後面添加了return this,將當前的this指針return回去,那麼就可以繼續調用函數中的方法了,實現鏈式調用;
小知識:
(1) 函數在沒有顯示的return的情況下,默認return undefined
(2)this是在一個類或者一個對象中,指向的是當前的類或者對象,那麼返回this之後,就可以繼續調用當前對象中屬性和方法了
******************************************************************************************************
*********************************demo地址!歡迎star*********************************************
******************************************************************************************************
原創不易,自由轉載,保留出處