Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 288
Holtorf Avatar asked Feb 22 '23 00:02

Holtorf


2 Answers

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"
like image 154
Blender Avatar answered Feb 23 '23 15:02

Blender


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.

like image 21
hugomg Avatar answered Feb 23 '23 16:02

hugomg