In JavaScript, you can set a variable equal to a method like this:
variable = function () { alert("My name is bob"); };
Or like this:
function SayMyName() {
alert("My name is bob");
}
variable = SayMyName;
You can also enclose a function with arguments like so:
function SayMyName(name) {
alert("My name is "+ name);
}
variable = function () { SayMyName("bob"); };
But trying to store a variable the following way will call the function, not store it as a variable:
function SayMyName(name) {
alert("My name is "+ name);
}
variable = SayMyName("bob");
There was a clever way you used to be able to work around this by using [callee][1], but callee is depreciated and won't work on most modern browsers.
Is there any way to set a variable equal to a function with arguments without using an enclosure?
Can't you use a nested anonymous function for this?
var variable = function(name) {
return function() {
alert('My name is ' + name);
};
};
Calling it yields your desired result:
var test = variable('bob');
test(); // Alerts "My name is bob"
You can use the bind
method to fix some parameters
var variable = SayMyName.bind(null, "bob");
However, this does not work in IE <= 8 so you would have to use a similar replacement or polyfil in tha case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With