JavaScript函数链式传参可行性及指定乘法函数实现问询
Yes, JavaScript absolutely supports this chained function pattern!
This is a classic example of function currying combined with overriding a function's valueOf method to make it behave like a primitive value when necessary. Here's how you can implement the mul function (you mentioned "MultiplyBy" but your examples use mul, so I'll stick with that for consistency):
function mul(x) { let product = x; // Define a nested function that accumulates the product const multiplier = function(y) { product *= y; return multiplier; // Return itself to allow chaining }; // Override valueOf so when the function is converted to a number, it returns the product multiplier.valueOf = function() { return product; }; return multiplier; }
How it works step-by-step:
- When you call
mul(2), it initializesproductto 2, creates themultiplierfunction, overrides itsvalueOfmethod, and returnsmultiplier. - Calling
mul(2)(3)invokesmultiplierwith 3:productbecomes 2 * 3 = 6, andmultiplieris returned again. - Calling
mul(2)(3)(4)invokesmultiplierwith 4:productbecomes 6 *4 =24, andmultiplieris returned. - When you pass this final
multiplierfunction toconsole.log, JavaScript automatically calls itsvalueOfmethod to convert it to a primitive value, so 24 is logged instead of the function's string representation.
Testing the examples:
console.log(mul(2)(3)(4)); // Output: 24 console.log(mul(4)(3)(4)); // Output: 48
This works perfectly as expected! If you want to use the name MultiplyBy instead of mul, just rename the function—everything else stays the same.
Content of this question originates from Stack Exchange, asked by Marcelo
相关产品推荐
相关产品推荐

