Holtorf Holtorf - 7 months ago 11
Javascript Question

Is it possible to set a variable equal to a function without using an enclosure?

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?

Answer

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.