I think there is something that i'm missing about method chaining. To me it feels incomplete.
Method chaining works by having each method return this so that another method on that object can be called. However, the fact that the return value is this and not the result of the function seems inconvenient to me.
Here is a simple example.
const Obj = {
result: 0,
addNumber: function (a, b) {
this.result = a + b;
return this;
},
multiplyNumber: function (a) {
this.result = this.result * a;
return this;
},
}
const operation = Obj.addNumber(10, 20).multiplyNumber(10).result
console.log(operation)
key points:
- Every method in the chain
Obj.addNumber(10, 20).multiplyNumber(10)returnsthis. - The last part of the chain
.resultis the one that returns a value other thanthis.
The problem with this approach is that it require you to tack on a property / method to get a value at the end other thanthis.
Compare this with built-in functions in JavaScript.
const str = " SomE RandoM StRIng "
console.log(str.toUpperCase()) // " SOME RANDOM STRING "
console.log(str.toUpperCase().trim()) // "SOME RANDOM STRING"
console.log(str.toUpperCase().trim().length) // 18
key points:
- Each function in the chain returns the result of the function not
this(maybe this is done under the hood) - No property / method is required at the end of the chain just to get the result.
Can we implement method chaining to behave the way built-in functions in Javascript behave?
this.operator is encountered. That does not happen when you have actual objects, thus the need to returnthisfrom methods intended to be used in chains of method calls.thisfor chaining. I just don't get how built in functions have return values at any point in the chain. for example const array = [["hellow","pastas"],["travel", "militarie"],["oranges","mint"]]; const arrayOne = array.map(e1 => e1.filter(e2 => e2.length > 6)).flat(); array.map has a return value which is then used in the chain for filter, and again by flat. Also, if the chain is reduced and you log that to the console the "this' object isn't logged but a result. (I know 'this' is being implemented... but it's not what we get back)String.prototype.toUpperCase()returns a string, a primitive value. The subsequent.operator causes that string to be implicitly cast to a new String instance. It's not magic, it's just the way expression evaluation works with.and primitive values.