Quiero cambiar mi código para ejecutar el encadenamiento. este es mi código:
let stepCount = { step: 0, up() { this.step++; }, down() { this.step--; }, showStep: function () { return this.step; } };
¿Cómo debo cambiarlo? Quiero ejecutar este código para obtener respuesta.
stepCount.up().up().down().up();
solo necesita devolver el objeto actual de cada función como esta
let stepCount = { step: 0, up() { this.step++; return this; }, down() { this.step--; return this }, showStep() { console.log(this.step) return this; } }; stepCount.up().up().down().showStep().down().showStep();
Esto debería hacer el trabajo:
class Step { constructor(count) { this.step = count; } up() { this.step++; return this; } down() { this.step--; return this; } } console.log(new Step(5).up().up().step); // 7