-1

I would like to do something like this:

"use strict"; // on by default in my babel setup
function create_func(some, params) {
    var func = otherstuff => {
        console.log("inner", some, otherstuff);
        return 4;
    };
    /*
      something here, such as:
      func.params = params;
    */ 
    return func;
}
var f = create_func(1,2);
console.log(f.params); // should print 2
var returnval = f(3); // should print "inner", 1, 3
console.log(returnval); // should print 4

This is related to eg how jQuery() is a function, but jQuery.ajax() is also an accessible function.

What would be the ideal way to do this in ES5, ES2015, or later?

Here's a question that asks how to do something similar to this, but without the constraint that it be modern JS: Can you create functions with custom prototypes in JavaScript?

lahwran
  • 601
  • 7
  • 22
  • 1
    Just assign `params` property to `func`, like `func.params = params`. What exactly here's wrong to you? – raina77ow May 30 '18 at 19:42
  • 1
    Functions are data and they are also objects in JavaScript. Learning how functions work is really what you need to investigate. This is not a question for Stack Overflow. – Scott Marcus May 30 '18 at 19:43
  • Oh, that's unexpected, it works when I run it in the browser. I'll have to edit the question, because the real problem seems to be something very different from this simply being not allowed. thanks! – lahwran May 30 '18 at 19:44
  • Sorry, what's wrong with what you have? The language hasn't changed that much since jQuery was created. At best you have `class`es now, where you could make the constructor be the function call, and it could have all the static properties you want... – Heretic Monkey May 30 '18 at 19:44
  • It appears that I already had working code, and I'm now confused as to why I was getting errors at all. – lahwran May 30 '18 at 19:46
  • voted to close. – lahwran May 30 '18 at 19:46
  • 1
    Possible duplicate of [Adding custom properties to a function](https://stackoverflow.com/questions/8588563/adding-custom-properties-to-a-function) – lahwran May 15 '19 at 18:42

1 Answers1

0

If your function is supposed to be a class with static properties, use class syntax.

Otherwise, you can use Object.assign:

function create_func(some, params) {
    return Object.assign(otherstuff => {
        console.log("inner", some, otherstuff);
        return 4;
    }, {params});
}

Of course simple assignment continues to work - there's no new syntax to create properties on function objects specifically.

Can you create functions with custom prototypes in JavaScript?

If that is what you are after (not just giving the function object custom properties), you can subclass Function since ES6 but it's not exactly convenient.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375