Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add(1)(2)(3).total === 6 - Has anyone else seen self returning functions used like this? [closed]

Tags:

javascript

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.

like image 621
user989370 Avatar asked Apr 17 '12 15:04

user989370


People also ask

What does () => mean in JavaScript?

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.

What is the output of following code console log sum 2 )( 3 ))?

The code result = sum(2)(3) is effectively the same as f = sum(2); result = f(3) , without the intermediate variable.

How do you return a function in JavaScript?

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.

How can you get the type of arguments passed to a function?

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.


1 Answers

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.

like image 115
Tejs Avatar answered Oct 02 '22 09:10

Tejs