0

Here is a simple example of what I want to be able to do.

I want a function returnFunctions which will take an integer N as an argument and will define the following functions:

func1(x) = x
func2(x) = 2*x
...
funcN(x) = n*x

How can I do something like this in javascript?

3
  • 3
    Why not just make somefunc(n, x)? Commented Aug 16, 2012 at 21:03
  • 2
    Wouldn't it be easier just to pass the multiplicand as another argument, rather than creating a function for every possible multiplicand? Or is this one of those contrived, only useful in the classroom things? Commented Aug 16, 2012 at 21:03
  • Robert, I believe it is the only way to go for the application I have in mind. I need to be able to call each function individually later on. Commented Aug 16, 2012 at 21:20

2 Answers 2

5

You can do like this:

function returnFunctions(n) {
  for (var i = 1; i <= n; i++) {
    (function(i){
      window['func' + i] = function(x) { return x * i; };
    })(i);
  }
}

Demo: http://jsfiddle.net/Guffa/H4juA/

However, it's not at all certain that it's the best solution for what you are trying to accomplish, but the question doesn't contain any information about that...

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

7 Comments

Thanks. Why is this request considered odd?
In my application each of these functions draws a separate movable point on a graph. I want n movable points labeled 1,2,...,n. For the sake of reusing code, it seemed like this was the way to go.
Well, it's never a good idea to have N similar functions. You should instead use just one function, and get the variable data from the point itself; instead of hard-coding i inside the function, pass the node as an argument to the function, or better yet, if your function is properly registered as an event listener, you can get hold of the element from the event that the function automatically receives. That would be a lot more memory efficient.
@StevenGubkin: Almost every request involving creating identifiers dynamically is odd. Using arrays or objects is usually a better solution.
I see. I am a mathematician who is very new to programming, th above was the natural thing to do from my tradition.
|
4

Something like this?

function Fn(n,x)
{ return n*x;
}

2 Comments

Perhaps a better option, but it's not at all what the OP asked for.
@Guffa I know, and thinking of that your answer is better i admit it, i just wrote an alternate solution in case the question was wrong... :P

Your Answer

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