JavaScript中的方法链接
链接方法,也称为层叠,是指以连续的一行代码在一个对象上反复调用一个方法。让我们看一个方法链接可以帮助我们避免重复的示例。
示例
以以下的轿车为例-
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
看看跑车重复了多少次?我们可以使用方法链接摆脱它。为此,不要让设置者仅设置值,而要在最后返回该值。这将使我们能够对对象执行操作。进行此更改后,我们的代码如下所示:
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
方法链接也称为流畅接口,因为它允许通过方法对对象进行操作,而不会通过重复对象而一次又一次中断流程。