Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Method Chaining ใน JavaScript

Chaining Methods หรือ Cascading หมายถึงการเรียกเมธอดต่อเนื่องบนออบเจ็กต์ในบรรทัดเดียว มาดูตัวอย่างที่ช่วยลดการซ้ำ

ตัวอย่าง

คลาส Car ตัวอย่าง

class Car {    constructor() {       this.wheels = 4       this.doors = 4       this.topSpeed = 100       this.feulCapacity = "400 Litres"    }    setWheels(w) {       this.wheels = w    }    setDoors(d) {       this.doors = d    }    setTopSpeed(t) {       this.topSpeed = t    }    setFeulCapacity(fc) {       this.feulCapacity = fc    }    displayCarProps() {       console.log(`Your car has ${this.wheels} wheels,\       ${this.doors} doors with a top speed of ${this.topSpeed}\       and feul capacity of ${this.feulCapacity}`)    } } let sportsCar = new Car(); sportsCar.setDoors(2) sportsCar.setTopSpeed(250) sportsCar.setFeulCapacity("600 Litres") sportsCar.displayCarProps()

ผลลัพธ์

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

เห็นไหม sportsCar ซ้ำมาก ใช้ method chaining ได้โดย return this ใน setters

class Car {    constructor() {       this.wheels = 4       this.doors = 4       this.topSpeed = 100       this.feulCapacity = "400 Litres"    }    setWheels(w) {       this.wheels = w;       return this;    }    setDoors(d) {       this.doors = d;       return this;    }    setTopSpeed(t) {       this.topSpeed = t;       return this;    }    setFeulCapacity(fc) {       this.feulCapacity = fc;       return this;    }    displayCarProps() {       console.log(`Your car has ${this.wheels} wheels,\       ${this.doors} doors with a top speed of ${this.topSpeed}\       and feul capacity of ${this.feulCapacity}`)    } }

ตอนนี้เขียนได้สวยขึ้น

ตัวอย่าง

let sportsCar = new Car()    .setDoors(2)    .setTopSpeed(250)    .setFeulCapacity("600 Litres")    .displayCarProps()

ผลลัพธ์

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

Method chaining เรียกอีกอย่างว่า fluent interface เพราะให้ทำงานกับออบเจ็กต์ผ่านเมธอดโดยไม่ต้องทำซ้ำออบเจ็กต์