How to convert string to function link in JavaScript?

I want to pass the name of the function as a string, and it will be as if I passed a link to this function. For example, I want to do the following:

var test = function(fn){
  fn();
}
test(alert);

Equally to this:

var test = function(function_as_string){
    //...code that converts function_as_string to function reference fn
    fn();
}
test('alert');

How can i do this?

+5
source share
5 answers

You get a link to the function from the window object:

var fn = window[function_as_string];

Demo: http://jsfiddle.net/Guffa/nA6gU/

+2
source

Use eval to get a reference to a function -

var Namespace = {
    quack: function () {console.log('quack!')}
};

function test (fnName) {
    var fn = eval(fnName);
    fn();
}
test('Namespace.quack')

This could potentially allow you to pass other arguments if you want.

, , [fnName], - $.ajax - window ['$. ajax'] undefined.. , , eval - .

+2

eval(), , javascript:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval

var test = function(fn){
  eval(fn + "()");
}
test(alert);

eval MDN:

eval() - , . eval() , -/. , , eval(), .

eval() , , JS-, JS.

( !) eval() .

: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval

+1

- . , () .

​var o = {};
​​​​
o.b = function b() {
    alert("b");
}

o.b();

o["b"]();

, .

function a() {
    alert("a");
}

a();

window.a();

window["a"]();

, , . :

function assignInside() {
    o.inside = function() {
        alert("inside");
    }
}

assignInside();
o["inside"]();

jsfiddle.

PS. In this case, there is no reason to use eval and many good reasons to avoid eval at all.

+1
source

What about:

var fn = new Function(function_as_string)
0
source

All Articles