简体   繁体   中英

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?

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!'); };

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.

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.

Make a new function!

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

Just need the function to return a function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM