The following code works, and while I understand why it works, I haven't seen it anywhere. I assume this is because all the other design patterns are much better.
I would still have expected to see the example as a cautionary tale along the line but I have not.
Sure, it is awful, especially with the example below which I chose because it is clear what it does but:
What is this pattern called?
Is it commonly used?
Are there any legitimate projects that use this pattern?
var add = function container (val) {
addFunc = function f (val, undefined) {
addFunc.total += val;
return addFunc;
};
addFunc.total = 0;
return addFunc(val);
};
alert(add(1)(2)(3).total);
alert(add(1)(2)(33).total);
Edit: Variable name change so that the code works in IE.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
The code result = sum(2)(3) is effectively the same as f = sum(2); result = f(3) , without the intermediate variable.
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
Technically, this could be considered chaining or encapsulation.
You chain when you can perform a set of operations indefinitely off an original function. jQuery uses a form of this when you can chain calls to set properties and attributes off an original selector. In this situation, the creator wanted to be able to chain calls to add without having to retype the function name. Not the cleanest of ideas, but valid.
Also, since the actual body of the code is never exposed to the caller, this could also be considered encapsulation since the addFunc
method is not exposed to the outside scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With