javascript實現鏈式呼叫簡單介紹

admin發表於2017-03-24

鏈式呼叫是jQuery的一大特色,可以有效的減少程式碼量和提高效率,jquery當然是由原生的javascript封裝而成的,鏈式呼叫的表現就是幾個函式用點連線是使用如下:

[JavaScript] 純文字檢視 複製程式碼
obj.a().b().c()

以上程式碼就是鏈式呼叫的表現,下面介紹一下如何實現鏈式呼叫。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<style type="text/css">
#thediv{
  width:100px;
  height:50px;
  background:green;
}
</style>
<script type="text/javascript">  
window.onload=function(){
  var odiv=document.getElementById("thediv");
  odiv.a=function(){
    this.style.width="200px";
    return this;
  }
  odiv.b=function(){
    this.style.height="200px";
    return this;
  }
  odiv.c=function(){
    this.style.backgroundColor="blue";
    return this;
  }
  odiv.a().b().c()
}
</script> 
</head> 
<body> 
<div id="thediv"></div>
</body> 
</html>

以上程式碼實現了鏈式呼叫效果,最關鍵的因素是函式的尾部都會返回物件本身。

相關文章