2

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;
}
5
  • 7
    It's basically currying. Commented Jul 28, 2013 at 7:17
  • What advantages does currying bring? Commented Jul 28, 2013 at 7:33
  • 3
    You don't have to pass the unchanging parameters every time. Commented Jul 28, 2013 at 7:35
  • 1
    or even know what they are or that they exist. it's decoupling. Commented Jul 28, 2013 at 8:54
  • @Kolink: en.wikipedia.org/wiki/… Commented Jul 28, 2013 at 11:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.