csss
csss

Reputation: 1997

Why is this syntax used in Javascript (returning a function from a function)

This code is from the AngularJS source code, which has alot of this 'function returning a function' style code.

function locationGetterSetter(property, preprocess) {
  return function(value) {
    if (isUndefined(value))
      return this[property];

    this[property] = preprocess(value);
    this.$$compose();

    return this;
  };
}

What advatanges does this have over just having a 'regular' function with extra parameters such as this -

function locationGetterSetter(property, preprocess, value) {
  if (isUndefined(value))
    return this[property];

  this[property] = preprocess(value);
  this.$$compose();

  return this;
}

Upvotes: 2

Views: 129

Answers (1)

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

In this case it would appear to be a function that's used to generate setter/getter functions for values.

Without seeing more context to where this is being used, one can only guess why it's done like this. However from the looks of it, I'd imagine it's being used to make it easier to generate dynamic objects with certain behaviors (eg. getting/setting values with certain validations).

Comparing to your alternative, it probably wouldn't even work like that considering the returned function uses the this keyword. Most likely it gets assigned into an object, thus this will refer to the object.

As pointed out in the comments it is essentially currying, but it's also possible the data used to generate the function is not available to pass as a parameter at the later stage where the generated function is being used, since angular does some compilation/linking with databinding where the info may only be available during the compilation/linking phase.

There also may be some very (very very) minor performance benefits from closing over the two parameters.

Upvotes: 1

Related Questions