Is it possible to set a variable to be equal to a function without using a shell?

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 wrap a function with arguments like this:

function SayMyName(name) {
   alert("My name is "+ name);
}
variable = function () { SayMyName("bob"); };

      

But when trying to store the variable, the following call will call the function rather than store it as a variable:

function SayMyName(name) {
   alert("My name is "+ name);
}
variable = SayMyName("bob");

      

There was a clever way you could work using [callee] [1], but the callable is deprecated and won't work in most modern browsers.

Is there a way to set a variable equal to a function with arguments without using a shell?

+3


source to share


5 answers


You can use the method bind

to fix some parameters

var variable = SayMyName.bind(null, "bob");

      



However, this doesn't work in IE <= 8, so you'll have to use a similar replacement or polyfilm in this case.

+3


source


Can't you use a nested anonymous function for this?

var variable = function(name) {
  return function() {
    alert('My name is ' + name);
  };
};

      



Calling this result gives the desired result:

var test = variable('bob');
test(); // Alerts "My name is bob"

      

+4


source


You can return a function like:

function SayMyName(x) { return function() { alert("My name is Bob.");}};

var x = SayMyName('bob');
x();

      

0


source


var name = (function sayMyName(name) {
    return alert('My name is: ' + name);
});
name('Mike');​​​​​

      

0


source


public class ToyProgram{

    public static void main(String[] args){
        String funcCallVar = aFunc();
        System.out.println(funcCallVar);
    }
    public static String aFunc(){
        String aVariable = "yes you can set a variale equal to a function";
        return aVariable;
    }
}

      

-1


source







All Articles