JavaScriptでのメソッドチェーン
連鎖メソッドは、カスケードとも呼ばれ、1つの連続したコード行で、オブジェクトに対して次々にメソッドを繰り返し呼び出すことを意味します。メソッドチェーンが繰り返しを回避するのに役立つ例を見てみましょう。
例
次のクラスの車を例にとってみましょう-
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が不必要に繰り返される回数を確認しますか?メソッドチェーンを使用することで、それを取り除くことができます。そのためには、セッターに値を設定させるのではなく、最後にこれを返します。これにより、オブジェクトに対して操作を実行できるようになります。この変更を行った後、コードは次のようになります-
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
メソッドチェーンは、オブジェクトを繰り返すことでフローを何度も中断することなく、メソッドを介してオブジェクトを操作できるため、流暢なインターフェイスとも呼ばれます。
-
JavaScriptのSort()メソッド
JavaScriptのsort()メソッドは、配列のソートに使用されます。並べ替えの順序は、アルファベット、数字、昇順、降順のいずれかです。 以下は、sort()メソッドのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /&
-
JavaScriptのObject.fromEntries()メソッド。
JavaScriptのObject.fromEntries()メソッドは、配列のように反復可能なマップを変換するために使用され、キーと値のペアを持つマップをオブジェクトに変換します。 以下は、Object.fromEntries()メソッドのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=devic