Accessing Global Function Pointer from its Name

A

anoop.kn

Is there anyway to access Global Function Pointer from its name ?
I want to call the function at runtime during a script execution.
PS: eval() works, I looking for a more efficient way of doing the
same !

Ex:

function testfunction ( msg )
{
alert( msg );
}

function onclickCallback( )
{
var fname = "testfunction";
/*
I want to call the function testfunction here by having access to its
name
without the use of eval. Is it possible ?
*/
}
 
J

Joost Diepenmaat

Is there anyway to access Global Function Pointer from its name ?
I want to call the function at runtime during a script execution.
PS: eval() works, I looking for a more efficient way of doing the
same !

Since global functions are properties of the global object, and the
global object is "window" (at least in browsers),
window[functionname](); should work.

That leaves us with the question of why you'd need the name at all since
you can refer to functions directly (which /should/ be more efficient):

function Bla() {
alert();
}

var f = Bla;

f();
 
S

Stevo

function testfunction ( msg )
{
alert( msg );
}

function onclickCallback( )
{
var fname = "testfunction";
/*
I want to call the function testfunction here by having access to its
name
without the use of eval. Is it possible ?

window[fname]("hello world");
 
T

Thomas 'PointedEars' Lahn

Joost said:
Since global functions are properties of the global object, and the
global object is "window" (at least in browsers),

You are jumping to conclusions.
window[functionname](); should work.

this[functioname]();

would work better in the global execution context.
That leaves us with the question of why you'd need the name at all since
you can refer to functions directly (which /should/ be more efficient):

function Bla() {
alert();
}

var f = Bla;

f();

Is there a point to this example?

As for the OP's code, the following should suffice:

// you may use an arbitrary identifier here
var _global = this;

function testfunction(msg)
{
window.alert(msg);
}

function onclickCallback()
{
var fname = "testfunction";

/*
I want to call the function testfunction here by having access
to its name without the use of eval. [...]
*/
_global[fname]("foo");
}

Note that it constitutes a security issue to have the method identifier read
from user input.

OP: This was a FAQ. Please search before you post.

http://jibbering.com/faq/


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,991
Messages
2,570,212
Members
46,800
Latest member
Tobi1987

Latest Threads

Top