zakdances
zakdances

Reputation: 23715

Assign an already-defined function to a variable with set arguments

I'd like something equivalent to this code, except I don't want my_func to be called when my_var is defined. I want to call my_var() later on in the code with the original argument ('called!') preserved.

function my_func(first_arg) {
alert(first_arg);
};
var my_var = my_func('called!');

How?

Upvotes: 0

Views: 1402

Answers (5)

millimoose
millimoose

Reputation: 39970

The straightforward way to implement this would be wrapping a call to your function with an argumentless anonymous function:

var my_var = new function() {
    my_func('called!');
}

ECMAScript 5th Edition introduces the Function.bind method that implements partial application (or more specifically currying), that would let you write this the following way:

var my_var = my_func.bind(undefined, 'called!');

(The undefined is there because the first parameter of bind() binds a value to the this "parameter".)

Function.bind() is relatively recent and not widely implemented. The Mozilla documentation includes a simple shim you could use to get most of the functionality. John Resig also has a blog post with a different implementation of partial application. It might also be available in one of the many many JS libraries.

Upvotes: 1

Andy E
Andy E

Reputation: 344665

You might be looking for something like Function.prototype.bind, which allows you to bind a function with arguments to a particular context. Basically, it allows you to do this:

function myFunc(firstArg, secondArg) {
    alert(firstArg + secondArg);
};

var myVar = myFunc.bind(null, 'called!');

myVar(' - from myVar!');
// result is alert with -> "called! - from myVar"

It's not in older browsers, but the link above has a compatibility implementation to make it work for this particular scenario.

Upvotes: 1

Shad
Shad

Reputation: 15461

Just need the function to return a function:

function my_func(first_arg) {
  return function(){alert(first_arg);}
};
var my_var = my_func('called!');

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237965

Make a new function!

function my_func(first_arg) {
    alert(first_arg);
};
var my_var = function() {
    my_func('called!');
}

Upvotes: 0

Blender
Blender

Reputation: 298364

Your function will be called when the variable is initialized (and the variable will then hold the output of your function, which isn't what you want). Why not make another function that returns the output of your function?

I'm bad at explaining things, so here's some code to stare at:

var my_var = function() { return my_func('called!'); };

Upvotes: 2

Related Questions