Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call javascript function which name is in variable [duplicate]

The problem is next: Assume that we have a select. Onchange event we need to call some function, but name of this function kept in variable. How to call this function ?

like image 846
user769154 Avatar asked Jul 29 '11 09:07

user769154


People also ask

Can function name and variable name be same in JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).

Can a variable and function have the same name?

Variables and functions have separate name spaces, which means a variable and a function can have the same name, such as value and value(), and Mata will not confuse them.

How do you call a function variable in JavaScript?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a function named my function in JavaScript?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


2 Answers

window[name]()

You can call functions by name reference by selecting them as a property of window and executing them

like image 93
Raynos Avatar answered Oct 11 '22 17:10

Raynos


have you tried variableName(); ?

We often pass around callback functions, which might look something like this

function doSomething(callbackFunction){
    // some happy code
    callbackFunction()
}
like image 34
Pwaddles Avatar answered Oct 11 '22 16:10

Pwaddles