const counter = function() {
let i = 0;
return {
add(val) {
i += val;
return this;
},
subtract(val) {
i -= val;
return this;
},
print() {
return i;
}
};
};
const outerCounter = counter();
outerCounter
.add(2)
.add(2)
.add(2)
.subtract(1)
.print(); // 5
We need to add return this;
inside the method which would return the entire object back so we could call another method. If we did not do this, it would return undefined
instead.