0

I have a scenario where I can pass a function or have it declared already. Since the function itself is not going to be used anywhere else I was planning to use an anonymous function instead, but the thing it's not working, so any help will be greatly appreciated.

As it is right now:

function connectStatic(connect, dir) {
  return connect.static(require('path').resolve(dir));
}

// ...
middleware: function (connect) {
  return [proxySnippet, connectStatic(connect, './')];
}
// ...

As I would like it to be:

// ...
middleware: function (connect) {
  return [proxySnippet, function () {
    return connect.static(require('path').resolve('./'));
  }];
// ...

Anyway, if I do:

// ...
middleware: function (connect) {
  return [proxySnippet, connect.static(require('path').resolve('./'))];
// ...

...it will works, but I'm wondering why it doesn't with the function declaration.

2 Answers 2

1

You need to invoke your anonymous function:

middleware: function (connect) {
  return [proxySnippet, (function () {
    return connect.static(require('path').resolve('./'));
  }())];

I wrapped your anonymous function with an optional additional level of parens just to help readability.

Here's an article with more information about self-executing functions: http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

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

2 Comments

That was quite right! Is there any reason to wrap the function between parentheses? I see there is no difference...at least in this case.
wrapping the function is optional. Some people may prefer the extra parens just because it makes the function look more like a unit, so feel free to skip them if you wish.
1

You're not actually calling your anonymous function, while in the "working" version, you are:

middleware: function (connect) {
  return [proxySnippet, function () {
    return connect.static(require('path').resolve('./'));
  }()];  // <--- change here
}

Now, given that the anonymous wrapper function doesn't really do anything, you should be able to get rid of it:

middleware: function (connect) {
  return [proxySnippet, connect.static(require('path').resolve('./'))];
})

Comments

Your Answer

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