views:

3157

answers:

6

I have a function like

function a (p1, p2) { /* ... */ }

and in some scope want to get something like this:

function b (/* no params! */) { return a (my1, my2) }

where my1 and my2 are defined somehow in this scope. So I should get a parameterless function b, which when called calls a with fixed parameters my1 and my2. Now, the question is, why this is not right, and which is :)

UPD: Ok, I had some callbacks in those params, now found out, how to process them all. What I missed was to apply the technique twice. Thank you.

A: 

Put the values in an array (or JSON) and return the array.

function a (p1,p2) { 
   var my = []
   my[0] = p1
   my[1] = p2
   return my
}

function b () {
    return a(my1,nmy2)
}

Maybe I'm missing the point in your example, I don't know.

Diodeus
It seems to me that you got me wrong (or maybe I was not strict enough). What I want is - having a function1, that takes some parameters, to generate a function2, that takes no parameters and returns function1 with some fixed parameters, not constant, certainly, they must be evaluated at that moment
stanch
A: 

Why is this not right? Are you getting an error? I tried to reproduce a working sample based one your description and what I have works so perhaps you could post a more detailed sample:

<script>

function a(p1, p2)
{
 return 'hello ' + p1 + ' and ' + p2;
}
function b(my1,my2)
{
 return function()
        {
          return a(my1,my2);
        }
}

var wrapper=b();
alert(wrapper());
</script>

Edit

Based on your comment to another answer I updated my sample to show how you can wrap a function.

Edit 2

Ok so I replaced them with variables;-)

JoshBerke
the problem is - my1 and my2 are not constants as in your example 'josh' and 'fred'. The must be evaluated at the time of creation of b.e.g. `var v='some text'; function b () {return a(v);}`
stanch
+2  A: 

Write a function that takes my1 and my2 and creates function b:

function make_b(my1, my2){
   return function b(){ return a(my1, my2);};
}
Matthew Marshall
+1  A: 

Just make a function that returns a new function b:

function getB(my1, my2) {
  return function() {
    a(my1, my2);
  }
}

and use it like this:

var b = getB(my1, my2);
JW
+1  A: 

I'm not sure if I understood you correctly, but you can look at a concept called currying. It is possible to curry a function in Javascript such that you can obtain another function with some or all of the parameters preset.

You can look at an implementation here.

If you are using Prototype, you can obtain the function b this way.

var b = a.curry(arg1, arg2);

now calling b() is the same as calling a(arg1, arg2)

Chetan Sastry
A: 

There appear to be three parts:

Defining a:

  function a(M, N) {
    return M + N;
  }

Defining b:

  var X = 10;
  var Y = 25;
  var b = function() {
   return a(X, Y);
}

Using b:

  var thirtyFive = b(); // thirtyFive = 35
Michael Brewer-Davis