I'm trying to understand how chaining functions work in JavaScript. I have two examples:
First
class Arithmetic {
constructor() {
this.value = 0;
}
add(value) {
this.value = this.value + value;
return this;
}
subtract(value) {
this.value = this.value - value;
return this;
}
}
You can do chain the methods by instantiating let a = new arithmetic();
and a.add(3).subtract(4);
Second
var zappo = function(selector) {
var el;
var obj = {
getEl(selector) {
return document.querySelector(selector);
},
addClass(className){
el.classList.add(className);
return this;
}
}
el = getEl(selector);
return obj;
}
I can chain these methods by zappo(#main).addClass("green").addClass("red");
My question is why is the first constructor function able to chain functions without having the methods within an object whereas the second function requires all the methods to be within an object?