Function Chaining
Function Chaining คือการเรียกใช้ฟังก์ชันหลายฟังก์ชันในบรรทัดเดียวโดยใช้ Dot Notation ทำให้โค้ดกระชับและเพิ่มประสิทธิภาพ บทความนี้จะสอน Function Chaining ด้วย Regular Objects
ก) ไม่ใช้ Function Chaining
ในตัวอย่าง สร้างออบเจ็กต์ 'obj' ที่มี property 'i' เริ่มต้นที่ 0 และมีเมธอด add(), subtract(), print() แต่ไม่มีการ return this ทำให้ไม่สามารถ chaining ได้ และแสดง undefined เมื่อพยายาม chaining
ตัวอย่าง
<html> <body> <script>
var obj = function(){
this.i = 0;
this.add = function(i){
this.i += i;
};
this.subtract = function(i){
this.i -= i;
};
this.print = function(){
document.write(this.i);
document.write("<br>");
document.write(x.add(3)); // returns undefined
}
}
var x = new obj();
x.add(5);
x.subtract(2);
x.print(); // 5-2 = 3 แสดง 3
x.add(5).subtract(2).print(); // Function chaining ไม่ได้ แสดง undefined
</script> </body> </html>
ผลลัพธ์
3 undefined
ข) ใช้ Function Chaining
เพิ่ม return this ในเมธอด add() และ subtract() ทำให้ chaining ได้และแสดงผล 3
ตัวอย่าง
<html> <body> <script>
var obj = function(){
this.i = 0;
this.add = function(i){
this.i += i;
return this;
};
this.subtract = function(i){
this.i -= i;
return this;
};
this.print = function(){
document.write(this.i);
}
}
var x = new obj();
x.add(5).subtract(2).print();
</script> </body> </html>
ผลลัพธ์
3