Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: return function with predefined arguments

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.

like image 843
stanch Avatar asked Mar 10 '09 16:03

stanch


1 Answers

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);
like image 96
JW. Avatar answered Sep 28 '22 18:09

JW.