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
.result
is 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?
CodePudding user response:
First of all, each of your console.log doesn't return properly:
console.log(str.toUpperCase.trim) //undefined
It returns undefined because str.toUpperCase returns the function object and does not execute the function itself so it won't work
The only correct usage is
console.log(str.toUpperCase().trim()
Now about your question, it is pretty easy to do it without a result and it is much more efficient.
Everything in javascript has a method called valueOf(), here is my example of calling everything like that for numbers, though I prefer just making functions instead of Objects.
const Obj = {
addNumber: function (a = 0) {
return a this.valueOf();
},
multiplyNumber: function (a = 1) {
return a*this.valueOf();
},
}
const nr = 2;
Object.keys(Obj).forEach(method => {
Number.prototype[method] = Obj[method];
})
console.log(Number.prototype); // will print out addNumber and multiplyNumber
// Now You can call it like this
console.log(nr.addNumber().multiplyNumber()); // Prints out 2 because it becomes (nr 0)*1
console.log(nr.addNumber(3).multiplyNumber(2)) // Prints out 10;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I think you are misunderstanding what method chaining actually is. It is simply a shorthand for invoking multiple methods without storing each intermediate result in a variable. In other words, it is a way of expressing this:
const uppercase = " bob ".toUpperCase()
const trimmed = uppercase.trim()
as this
const result = " bob ".toUpperCase().trim()
Nothing special is happening. The trim
method is simply being called on the result of " bob ".toUpperCase()
. Fundamentally, this boils down to operator precedence and the order of operations. The .
operator is an accessor, and is evaluated from left to right. This makes the above expression equivalent to this (parens used to show order of evaluation):
const result = (" bob ".toUpperCase()).trim()
This happens regardless of what is returned by each individual method. For instance, I could do something like this:
const result = " bob ".trim().split().map((v,i) => i)
Which is equivalent to
const trimmed = " bob ".trim()
const array = trimmed.split() //Note that we now have an array
const indexes = array.map((v,i) => i) //and can call array methods
So, back to your example. You have an object. That object has encapsulated a value internally, and adds methods to the object for manipulating the results. In order for those methods to be useful, you need to keep returning an object that has those methods available. The simplest mechanism is to return this
. It also may be the most appropriate way to do this, if you actually are trying to make the object mutable. However, if immutability is an option, you can instead instantiate new objects to return, each of which have the methods you want in the prototype. An example would be:
function MyType(n) {
this.number = n
}
MyType.prototype.valueOf = function() {
return this.number
}
MyType.prototype.add = function(a = 0) {
return new MyType(a this)
}
MyType.prototype.multiply = function(a = 1) {
return new MyType(a * this)
}
const x = new MyType(1)
console.log(x.add(1)) // { number: 2 }
console.log(x.multiply(2)) // { number: 2 }
console.log(x.add(1).multiply(2)) // { number: 4 }
console.log(x.add(1).multiply(2) 3) // 7
The key thing to note about this is that you are still using your object, but the valueOf
on the prototype is what allows you to directly utilize the number
as the value of the object, while still making the methods available. This is shown in the last example, where we directly add 3 to it (without accessing number
). It is leveraged throughout the implementation by adding this
directly to the numeric argument of the method.
CodePudding user response:
Method chaining is the mechanism of calling a method on another method of the same object in order to get a cleaner and readable code.
In JavaScript method chaining most use the this
keyword in the object's class in order to access its method (because the this
keyword refers to the current object in which it is called)
When a certain method returns this, it simply returns an instance of the object in which it is returned, so in another words, to chain methods together, we must make sure that each method we define has a return value so that we can call another method on it.
In your code above, the function addNumber returns the current executing context back from the function call. The next function then executes on this context (referring to the same object), and invokes the other functions associated with the object. it's is a must for this chaining to work. each of the functions in the function chaining returns the current Execution Context. the functions can be chained together because the previous execution returns results that can be processed further on.
This is part of the magic and uniqueness of JavaScript, if you're coming from another language like Java or C# it may look weird for you, but the this
keyword in JavaScript behaves differently.
CodePudding user response:
To avoid the necessity of this
, maybe something static works for you?
const myNum = (n = 1) => ({
add: x => myNum(n x),
multiply: x => myNum(n * x),
divide: x => myNum(n / x),
get roundUp() { return myNum(Math.ceil(n)); },
get roundDown() { return myNum(Math.floor(n)); },
get result() { return n; }
});
console.log(
myNum(42)
.add(3)
.multiply(5)
.divide(3)
.roundUp
.multiply(7)
.divide(12)
.add(-1.75)
.result);
const myStr = (str = ` Hello world `) => ({
get trim() { return myStr(str.trim()); },
get upper() { return myStr(str.toUpperCase()); },
get len() { return str.length; },
insertAt: (at, insertStr) => myStr(str.slice(0, at) insertStr str.slice(at)),
get result() { return str; }
});
const upperTrimmed = myStr().upper.trim.insertAt(6, `cruel coding `).upper;
console.log(`[${upperTrimmed.result}] has length ${upperTrimmed.len}`);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>