I want to programmatically reach a method that is nested inside a object.
var app = {
property:{
method:function(){},
property:"foo"
}
}
Normally you would access it like so: app.property.method
But in my case, In runtime I get a string that I want to interpolate that into calling the method function
Now, how can method be accessed programmatically when i have the following string
"app.property.method"
For a reference please see:
http://jsfiddle.net/adardesign/92AnA/
A while ago I wrote this little script to get an object from the string describing its path:
(function () {
"use strict";
if (!Object.fromPath) {
Object.fromPath = function (context, path) {
var result,
keys,
i;
//if called as `Object.fromPath('foo.bar.baz')`,
//assume `window` as context
if (arguments.length < 2) {
path = context;
context = window;
}
//start at the `context` object
result = context;
//break the path on `.` characters
keys = String(path).split('.');
//`!= null` is being used to break out of the loop
//if `null` or `undefined are found
for (i = 0; i < keys.length && result != null; i+= 1) {
//iterate down the path, getting the next part
//of the path each iteration
result = result[keys[i]];
}
//return the object as described by the path,
//or null or undefined if they occur anywhere in the path
return result;
};
}
}());
You'd need to use bracket notation (i'd avoid the other option - eval()). If the app variable is global, then it would be a property of the window object:
executeFunctionByName("app.property.method", window);
Method borrowed from: How to execute a JavaScript function when I have its name as a string
The method essentially just breaks your window["app.property.method"] (which would fail) into window["app"]["property"]["method"] (which works).
You could try this:
var methodString = "app.property.method";
var method = eval(methodString);
Then method will be a function pointer which may be called like so:
method();
Related
I am trying to create function findStrings which should share it's variables with the function init, stringSplit and stringSearch.
String.prototype.findStrings = (function () {
var action = 'split';
var params = ',';
var init = function (action = 'split', params = ',')
{ this.stringSplit(); }
var stringSplit = function (action)
{ return this.init(); }
var stringSearch = function (action)
{return this.init(); }
return init;
})();
What I need.
When I call test.findStrings('split'); it should 1) initiate variables by calling init 2) then call stringSplit so this should be string test.
When I call var result = test.findStrings( 'search', { params ... } ); 1) initiate variables, process arguments from object params 2) then call stringsSearch and this should be test.
var test = '#a > :matches(.b, #c)';
test.findStrings('split', "," );
var result = test.findStrings( 'search', { params ... } );
Error which I got is saying that this does not have stringSplit (because this is Window) and I need to this to be test.
How to access the test string within the functions and make it possible to access the variables and arguments within them?
Actually, I could remove the function searchStrings to simplify it.
Solution:
String.prototype.findStrings = (function () {
var text = this;
...
String.prototype.init = function (action = 'split', params = ',') {
text.stringSplit();
}
}
There were two errors.
I need to this to be test.
When init() is first called, this does equal test. The problem is that stringSplit and stringSearch are just variables, and have nothing to do with the current context.
Either way, the code is pretty difficult to understand. If you really want to override String, then why don't you do something like:
String.prototype.findStrings = function(action = 'split', params = ',') {
// do logic here (not entirely sure what you want to accomplish)
return (action === 'split') ? this.stringSplit() : this.stringSearch();
}
// Add other functions also to string prototype
String.prototype.stringSplit = function() { ... }
String.prototype.stringSearch = function() { ... }
Personally though, I don't like adding methods to types like String for various reasons. Why not adopt a more functional approach, and create functions that you simply pass strings to, and get an appropriate result?
For example:
function findStrings(str, params){
// do logic and return result
}
First of all, you have a circular reference in your code: the init function calls stringSplit which calls init.
But to reach to that problem you should remove the this keyword from your prototype function. this will get the value of the object that is calling your function, in your case the window object, but your functions are created in a closure so you can't access them using the window object.
I am using history.js. In the stateObj of the pushState function, I want to add a reference to a function (Car.init(), or Boat.init(). In C++, I believe I could use a function pointer.
Then on window.onpopstate, I want to reference that function and call it. I can read the string (Car.init(), but then how can I call the function? I don't want to use eval.
You probably shouldn't, but if you do want to invoke a function based on a global dotted-path name, that could be accomplished like this:
function callFunction(name, var_args) {
// break the string into individual property/method names
var parts = name.split('.');
// start with a reference to the global object
var target = window;
var previousTarget = null;
for (var i = 0; i < parts.length; i++) {
// keep a copy of the previous reference to use as the `this` value
previousTarget = target;
// change the reference to the next named property
target = target[parts[i]];
}
// grab the remaining arguments
var args = Array.prototype.slice.call(arguments, 1);
// call the target function, with previousTarget as the subject, using args
return target.apply(previousTarget, args);
}
// This is in the top-level/global scope. This won't work for a local definition.
var MyApp = {
currentUser: {
name: 'Joe',
displayName: function(greeting) {
alert(greeting + " ," + this.name + "!");
}
},
openBar: function() {
alert("The Foo Bar is now open for business!");
}
};
var functionName = 'MyApp.currentUser.displayName';
callFunction(functionName, "Hello");
This is safer than using eval (good call on avoiding it), but is still pretty wacky and very difficult for JavaScript interpreters to optimize. Instead, the recommended approach is to use a reference (pointer) to the function. This is probably similar to what you'd do in C++. If the function doesn't use this (i.e. if it's a static function, not a method), you can just take a reference to the function directly.
var open = MyApp.openBar;
open();
If it does have a this value, you'll need to use the .bind() method to preserve its association with the object it's attached to.
var display = MyApp.currentUser.displayName.bind(MyApp.currentUser);
display("Greetings");
If you pass additional arguments to .bind(), you can also specify the leading arguments that will be used to call the function.
var displayHello = MyApp.currentUser.displayName.bind(MyApp.currentUser, "Hello");
displayHello();
In a typical js class, all calls to member functions must be preceded by this. I was looking at a technique that would let me create a library of inter-dependent STATIC functions and relying on closure/scope to make things a bit easier.
Example:
var Singleton={
//main entry point
// call with fn name, args...
call:function(){
var args=[];
if (arguments.length==0) {
return;
}
// get the fn name
var fn=arguments[0];
var x;
// make args array
for (x=1;x<arguments.length;x++) {
args[args.length]=arguments[x];
}
// I want to get rid of this part
// See below for what I wish
// Here I have access to fns below due to hoisting in js
// so I put them in a map...
var fns={
test:test
// etc, more like this I do not want to type/maintain
}
// ... all so I can do this
// get my function.
var fun=fns[fn];
// instead of that, I would like to "override whitespace" and
// say something like:
// var fun=['fn_name'];
// so I can index into local scope and get a fn
//
// log error if not found
if (typeof fun=='undefined') {
loge('Singleton: function not found:'+fn);
return;
}
// ok, run the function
return fun.apply(window,args);
// the test fn accesses test2() without dot notation
function test(a){
// Note: here in test fn it can access test2()
// without using this.test2() syntax
// as you would in normal objects
var s=test2();
alert(s+' test:'+a);
};
function test2(){
return 'test2';
};
}
}
I was hoping someone more familiar with advances in javascript might have advice on how to emulate an "implied but unnecessary this", it always struck me as strange that this defaults to window, and wouldn't it be nice if this could be pointed to an anonymous object with the local scope attached.
I would love to say ['localObject'] to get something in scope.
Edit:
After seeing some of the responses, I will restate this in the form of a challenge:
What I am looking for is a syntax cheat, a way to, as #Varuna put it, "1. Access static methods without using this variable i.e. they will remain global to one another. 2. Do not want to maintain a local array for static methods and want to achieve with in the local scope itself."
Put differently, I need to have the declared functions Register themselves, but I don't want to state the function name more than once. I suppose #Varuna has a solution using eval to access the local scope.
The following approach wont work:
var o={};
o['fn']=function fn(){};
o['fn2']=function fn2(){};
...because you have to state the fn name twice, but closure is preserved.
And this:
var a=[
function fn(){}
,function fn2(){}
];
Register(a);
Will not work because, AFAIK, you lose closure, ie. fn2 cannot see fn. Which also makes the following declarative style a "this nightmare":
window.MINE={
fn:function fn(){
//this?
// want to say fn2(), not this.fn2(), nor MINE.fn2()
}
,fn2:function fn2(){
//this?
}
,deeper:{
//more
}
};
But something like this might work, if you created a weird property that does the registration on assignment:
var registar=new Registar();
registar.reg=function fn(){};
registar.reg=function fn2(){};
//then access
var fn=registar.getFn(n);
// or
var fn=registar._[n];
The above relies on js properties and having access to fn.name, which is not available in all cases AFAIK.
If I understand correctly, you want to create objects that:
have static members
... which can be accessed without using the this notation
The easiest solution (assuming I've properly understood your query), would be to simply use a closure to store your stratic fields, access them directly by name, then explicitly add them as object members.
Consider:
var myConstructor = (function(){
var foo = 'someStaticField';
var bar = function(){
alert('A static method returns ' + foo);
};
return function(){
return {
foo : foo,
bar : bar
};
};
})();
var myInstance = new myConstructor();
As per my understanding, you want to:
1. Access static methods without using this variable i.e. they will remain global to one another.
2. Do not want to maintain a local array for static methods and want to achieve with in the local scope itself.
You can check whether a method exist using eval.Check Here
Only drawback is that this will be using eval method.
Code will be:
var Singleton = {
//main entry point
// call with fn name, args...
call: function () {
var args = [];
if (arguments.length == 0) {
return;
}
// get the fn name
var fn = arguments[0];
var x;
// make args array
for (x = 1; x < arguments.length; x++) {
args[args.length] = arguments[x];
}
//check whether function exist in local scope and not in global scope
if (typeof eval(fn) !== 'undefined' && typeof window[fn] === 'undefined') {
// ok, run the function
return eval(fn).apply(window, args);
}
else{
// log error if not found
loge('Singleton: function not found:' + fn);
return;
}
// the test fn accesses test2() without dot notation
function test(a) {
// Note: here in test fn it can access test2()
// without using this.test2() syntax
// as you would in normal objects
var s = test2();
alert(s + ' test:' + a);
};
function test2() {
return 'test2';
};
}
}
How about declaring functions that can access each other in separate closure, and exporting them to main method by binding your call method to an object containing the functions? Something like previous post (modified slightly):
var Singleton = {
call: (function() {
// here 'call' is bound to object containig your test functions
// this: {test, test2}
if (0 == arguments.length) return;
// log error if not found
if ('function' != typeof this[arguments[0]]) {
console.warn('Singleton: function not found:' + arguments[0]);
return;
}
// '...index into local scope and get function
// ie. get the function by it's name
return this[arguments[0]].
apply(window, Array.prototype.slice.call(arguments, 1));
// --- or:
// you can explicitly introduce function names to current scope,
// by `eval`-ing them here (not very much preferred way in JavaScript world):
for (var fname in this)
if (this.hasOwnProperty(fname))
eval('var ' + fname + ' = ' + this[fname]);
// and you can reference them directly by using their names
var fn = eval(arguments[0]);
return fn.apply(window, Array.prototype.slice.call(arguments, 1));
}).bind(
(function() {
var _exports = {};
function test (a) {
var s = test2();
alert(s + ' test: ' + a);
}
function test2 () {
return 'test2';
}
_exports['test'] = test;
_exports['test2'] = test2;
return _exports;
})()
)};
Singleton.call('test', 'foo and stuff');
//
previous post:
You are talking about Function#bind functionality that enables 'customizing' function's context. .bind() your call method to required 'local context' like this:
var Singleton = {
//main entry point
// call with fn name, args...
call: (function() {
// here `this` (context) is object bound to `call` method
// not `global` object, which is default for 'unbound' functions
var locals = this; // {fns, shift, loge, isfunc}
var fn;
var fun;
var x;
if (arguments.length == 0)
return;
// get the fn name
fn = locals.shift(arguments);
// '...index into local scope and get a fn'
fun = locals.fns[fn];
// log error if not found
if (!locals.isfunc(fun)) {
locals.loge('Singleton: function not found:' + fn);
return;
}
// ok, run the function
return fun.apply(window, arguments);
// lock `call`'s context to provided object
// and use `this` to reference it inside `call`
}).bind({
fns: (function(_) {
// and you can '...create a library of inter-dependent STATIC functions'
// in this closure and invoke them in `call` method above
_.test = function (a) {
var s = _.test2();
alert(s + ' test: ' + a);
};
_.test2 = function() {
return 'test2';
};
return _;
})({}),
// and create couple of helper methods as well...
isfunc: (function(_getclass) {
_getclass.func = _getclass(_getclass);
return ('function' !== typeof(/foo/)) ?
function(node) {
return 'function' == typeof node;
} :
function(node) {
return _getclass.func === _getclass(node);
};
})(Function.prototype.call.bind(Object.prototype.toString)),
loge: console.warn,
shift: Function.prototype.call.bind(Array.prototype.shift)
}),
};
Singleton.call('test', 'foo and stuff');
// eof
Here's one 'in your face answer', because I really don't like what I see here.
I don't see why you need this kind of construct, you already have that as part of language core.
1. dynamic lookup
you are doing it in a rather 'unprecedented' kind of way,
hashes already do that for you, and it's lightning fast to do a hash search.
If you are eval()-ing random strings to do simple name lookup you really have to
step aside from a keybord for a while... (no offense please)
2. closures
you are saying about 'using closures' which you actualy don't use.
your call function redeclares test functions each time it gets called,
and looks the ('fresh version') functions in it's own variable scope table,
instead of lookig them up in parent scope chains (aka. closures)
outside it's lexical location
3. nfe vs. nfd
ie. named function expressions vs. named function declarations
...you cannot assign a function to a local var and have it retain closure.
It is a feature, you might not be aware of how it works (it tripped me up as well).
check this article out for clarification
4. exceptions
Singleton: function name not found... x4!
Just go ahead and call a function,
interpreter will throw for you anyway if it cannot find/execute
5. eval (aka. ^^)
Singleton.call.ctx.fun = eval(Singleton.call.ctx.fn);
eval takes any string here(#!), and gladly executes ones like:
'for(;;);', or 'while(1);'... forever.
You probably don't want to have any code running unless it was your stuff.
6. arguments handling
It is considered best practice out there to use single (Object) options parameter
to 'fine tune' any significant piece of bundled functionality,
instead of trying to figure that out by type checking provided argument list
Here's, in couple of simple lines, what I (and as I can see #Jimmy Breck-McKye) suggest you should do:
var Singleton.call = (function () {
var funcmap = {
'f_1': function () {},
// etc.
'f_N': function () {},
};
return function (options) {
// options members:
// context, (Object) context, (defaults to global if none is given)
// func, (String) function_name,
// args, (Array) arguments to pass into a function
// this line does everything your 100+ lines long snippet was trying to:
// look's up parent scope for a function, tries to run it
// passing provided data, throws if it gets stuck.
return funcmap[options.func].apply(options.context, options.args);
};
})();
//
Answering my own question here.
The core of the issue is that you cannot assign a function to a local var and have it retain closure.
Consider that when writing a function with global and window scope, this is not necessary to call another function with identical scope. Such is not the case with member functions.
Another way of saying this is that there is no space where your cursor can sit and as you declare a function it automatically gets attached to the current this.
function fn(){}// if we are in global scope, then window.fn becomes defined
// but if we are inside, say, a constructor, simple declaration will not attach
// it to this, but fn is available in scope.
Any assignment on function declaration BREAKS part of the expected closure:
var IdentifierAvailableToClosure=function Unavailable(){}
But assignment after declaration works:
function NowAvailable(){}
var SynonymAvailableToo=NowAvailable;
This is what I meant by not wanting to repeat the name twice to get the mechanism to work.
This fact made me abandon other methods and rely on eval as suggested. Here is a first draft:
// This object is an encapsulation mechanism for a group of
// inter-dependent, static-ish, functions that can call each other
// without a this pointer prefix.
// Calls take the form of:
// Singleton.call(functionName:String [,arg1]...)
// or
// Singleton.call(contextObject:Object, functionName:String [,arg1]...)
// If a context is not provided, window is used.
//
// This type of mechanism is useful when you have defined a group
// of functions in the window/global scope and they are not ready
// to be formalized into a set of classes, or you have no intention
// of doing that
//
// To illustrate the issue, consider that a function
// which is defined in window/global scope
// does not have to use the this pointer to call a function of
// identical scope -- yet in a class member function, the this pointer
// MUST be used
// Therefore, trying to package such functions requires injecting
// the this pointer into function bodies where calls to associater
// functions are made
//
// Usage is primarily for development where one has control over
// global namespace pollution and the mechanism is useful in
// refactoring prior to formalization of methods into classes
var Singleton={
// Main call point
call:function(){
// Bail with error if no args
if (arguments.length==0) {
throw('Singleton: need at least 1 arg');
}
// As all functions in the local scope library below
// have access to the local scope via closure, we want to reduce
// pollution here, so lets attach locals to this call
// function instead of declaring locals
//
// Prepare to call anon fn
Singleton.call.args=arguments;
// Make ctx have args, context object, and function name
Singleton.call.ctx=(function (){// return args,ctx,name
// out
var args=[];
//locals
var x, fn;
// collapse identifier
var a=Singleton.call.args;
// closure object avail to functions, default to window
that=window;
// first real function argument
var arg_start=1;
// first arg must be function name or object
if (typeof a[0]=='string') {// use window ctx
fn=a[0];
// if first arg is object, second is name
}else if (typeof a[0]=='object') {
// assign given context
that=a[0];
// check second arg for string, function name
if (typeof a[1]!='string') {
var err='Singleton: second argument needs to be a fn name'
+' when first arg is a context object';
throw(err)
return;
}
// ok, have a name
fn=a[1];
// args follow
arg_start=2;
}else{
// improper arg types
var err='Singleton: first argument needs to be a string or object';
throw(err)
}
// build args array for function
for (x=arg_start;x<a.length;x++) {
args[args.length]=a[x];
}
// return context
return {
args: args
,that:that
,fn:fn
};
})();
// using function library present in local scope, try to find specified function
try{
Singleton.call.ctx.fun=eval(Singleton.call.ctx.fn);
}catch (e){
console.error('Singleton: function name not found:' + Singleton.call.ctx.fn);
throw('Singleton: function name not found:' + Singleton.call.ctx.fn);
}
// it must be a function
if (typeof Singleton.call.ctx.fun !== 'function') {
console.error('Singleton: function name not found:' + Singleton.call.ctx.fn);
throw('Singleton: function name not found:' + Singleton.call.ctx.fn);
}
// library functions use that instead of this
// that is visible to them due to closure
var that=Singleton.call.ctx.that;
// Do the call!
return Singleton.call.ctx.fun.apply(that, Singleton.call.ctx.args);
//
// cool library of functions below,
// functions see each other through closure and not through this.fn
function test(s){
alert(test2()+' test:'+s);
}
function info_props(){
console.info(this_props());
}
function test2(){
return 'test2';
}
function this_props(){
var s='';
for (var i in that) {
s+=' '+i;
}
return s;
};
}
};
I want to check if a function is defined (I don't care how, I mean it is callable)
sample code:
var functions = {
'alert':'alert',
'undefinedFunction':'undefinedFunction',
'ff.showAlert':'ff.showAlert'
};
var ff = {
showAlert: function() {
alert('the function works');
}
};
for (i in functions) {
console.log(i+' : '+typeof window[functions [i]]);
}
this returns:
alert : function
undefinedFunction : undefined
ff.showAlert : undefined
console.log(typeof window.ff.showAlert); return function
Live demo
Is there a way to programmatically check if a function exists?
The code:
window[functions [i]]
Is checking for window['ff.showAlert'] but what you really want to check for is:
window['ff']['showAlert']
or
window.ff.showAlert
For this, you need to traverse the namespace (window->ff->...):
function methodIsDefined(fn, obj) {
var ns = fn.split('.');
fn = ns.pop();
do {
if (!ns[0]) {
return typeof obj[fn] === 'function';
}
} while(obj = obj[ns.shift()]);
return false;
}
E.g.
methodIsDefined('ff.showAlert', window); // => true
methodIsDefined('ff.foo', window); // => false
Your problem lies within the namespacing. The string "ff.showAlert" does not reference to the function window['ff']['showAlert'], but to window['ff.showAlert'], which is an important difference. The function you declare is actually referenced by window['ff']['showAlert']. So the place, that you are checking for its existance, is wrong.
If you want to check for the existance of such namespaced functions, you first have to split the string and then walk through the DOM to find the correct property. The code would be something like the following (not tested!):
function checkFunction( name ) {
var path = "ff.showAlert".split( '.' ),
runner = window;
for( var i=0; i<path.length; i++ ) {
if( path[i] in runner ) {
runner = runner[ path[i] ];
} else {
return false;
}
}
return runner;
}
edit
As pointed out by #VirtualBlackFox in the comments: The above solution only works if the function is declared below the window-scope. If it's inside another function's scope, you would have to pass that scope as an additional parameter and search there.
Even in that case you can't check for the existance of functions that are, e.g., defined inside some closure constructs.
You need to split multi-part function names like 'ff.showAlert'. Also, because you specified ff as a var, it won't be a member of window unless it's outside of any function scope. It's not really clear whether it is or not from your code example.
Anyway, the function below allows you to pass in a base object, in case you need to specify one other than window, and it splits multi-part function names:
function isFnDefined(fnName, baseObj) {
try {
var parts = fnName.split('.'),
ii;
// If no baseObj was provided, default to 'window'.
baseObj = baseObj || window;
for (ii in parts) {
baseObj = base[parts[ii]];
}
return typeof baseObj === 'function';
}
catch (e) {
return false;
}
}
isFnDefined('alert'); // returns true
isFnDefined('undefinedFunc'); // returns false
isFnDefined('ff.showAlert'); // returns true, if ff is a member of window
isFnDefined('showAlert', ff); // returns true
you need to use eval(): http://www.w3schools.com/jsref/jsref_eval.asp
You have a string that represent something in the current scope and you want to know what it is, the solution is to eval the string.
var f = undefined;
try
{
f = eval(functions[i]);
}
catch(ReferenceError) {}
console.log(typeof f);
But why are you storing strings instead of function themselves in your input object ?
Also if you could force every string to be a reference relative to window (No 'var' in the current scope or something coming from the closure of another scope) then #Sirko solution might be the best one.
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 9 years ago.
I got a string like:
settings.functionName + '(' + t.parentNode.id + ')';
that I want to translate into a function call like so:
clickedOnItem(IdofParent);
This of course will have to be done in JavaScript. When I do an alert on settings.functionName + '(' + t.parentNode.id + ')'; it seems to get everything correct. I just need to call the function that it would translate into.
Legend:
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
Seeing as I hate eval, and I am not alone:
var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Edit: In reply to #Mahan's comment:
In this particular case, settings.functionName would be "clickedOnItem". This would, at runtime translate var fn = window[settings.functionName]; into var fn = window["clickedOnItem"], which would obtain a reference to function clickedOnItem (nodeId) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id), which equals clickedOnItem(t.parentNode.id), which was what the OP wanted.
More full example:
/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};
/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}
/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
window[settings.functionName](t.parentNode.id);
No need for an eval()
Here is a more generic way to do the same, while supporting scopes :
// Get function from string, with or without scopes (by Nicolas Gauthier)
window.getFunctionFromString = function(string)
{
var scope = window;
var scopeSplit = string.split('.');
for (i = 0; i < scopeSplit.length - 1; i++)
{
scope = scope[scopeSplit[i]];
if (scope == undefined) return;
}
return scope[scopeSplit[scopeSplit.length - 1]];
}
Hope it can help some people out.
JavaScript has an eval function that evaluates a string and executes it as code:
eval(settings.functionName + '(' + t.parentNode.id + ')');
eval() is the function you need to do that, but I'd advise trying one of these things to minimize the use of eval. Hopefully one of them will make sense to you.
Store the function
Store the function as a function, not as a string, and use it as a function later. Where you actually store the function is up to you.
var funcForLater = clickedOnItem;
// later is now
funcForLater(t.parentNode.id);
or
someObject.funcForLater = clickedOnItem;
// later is now
(someObject.funcForLater)(t.parentNode.id);
Store function name
Even if you have to store the function name as a string, you can minimize complexity by doing
(eval(settings.functionName))(t.parentNode.id);
which minimizes the amount of Javascript you have to construct and eval.
Dictionary of handlers
Put all of the action functions you might need into an object, and call them dictionary-style using the string.
// global
itemActions = { click: clickedOnItem, rightClick: rightClickedOnItem /* etc */ };
// Later...
var actionName = "click"; // Or wherever you got the action name
var actionToDo = itemActions[actionName];
actionToDo(t.parentNode.id);
(Minor note: If instead here you used syntax itemActions[actionName](t.parentNode.id); then the function would be called as a method of itemActions.)
While I like the first answer and I hate eval, I'd like to add that there's another way (similar to eval) so if you can go around it and not use it, you better do. But in some cases you may want to call some javascript code before or after some ajax call and if you have this code in a custom attribute instead of ajax you could use this:
var executeBefore = $(el).attr("data-execute-before-ajax");
if (executeBefore != "") {
var fn = new Function(executeBefore);
fn();
}
Or eventually store this in a function cache if you may need to call it multiple times.
Again - don't use eval or this method if you have another way to do that.
I wanted to be able to take a function name as a string, call it, AND pass an argument to the function. I couldn't get the selected answer for this question to do that, but this answer explained it exactly, and here is a short demo.
function test_function(argument) {
alert('This function ' + argument);
}
functionName = 'test_function';
window[functionName]('works!');
This also works with multiple arguments.
If settings.functionName is already a function, you could do this:
settings.functionName(t.parentNode.id);
Otherwise this should also work if settings.functionName is just the name of the function:
if (typeof window[settings.functionName] == "function") {
window[settings.functionName](t.parentNode.id);
}
This took me a while to figure out, as the conventional window['someFunctionName']() did not work for me at first. The names of my functions were being pulled as an AJAX response from a database. Also, for whatever reason, my functions were declared outside of the scope of the window, so in order to fix this I had to rewrite the functions I was calling from
function someFunctionName() {}
to
window.someFunctionName = function() {}
and from there I could call window['someFunctionName']() with ease. I hope this helps someone!
I prefer to use something like this:
window.callbackClass['newFunctionName'] = function(data) { console.log(data) };
...
window.callbackClass['newFunctionName'](data);
Based on Nicolas Gauthier answer:
var strng = 'someobj.someCallback';
var data = 'someData';
var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
//We maybe can check typeof and break the bucle if typeof != function
func = func[funcSplit[i]];
}
func(data);
In javascript that uses the CommonJS spec, like node.js for instance you can do what I show below. Which is pretty handy for accessing a variable by a string even if its not defined on the window object. If there is a class named MyClass, defined within a CommonJS module named MyClass.js
// MyClass.js
var MyClass = function() {
// I do stuff in here. Probably return an object
return {
foo: "bar"
}
}
module.exports = MyClass;
You can then do this nice bit o witchcraft from another file called MyOtherFile.js
// MyOtherFile.js
var myString = "MyClass";
var MyClass = require('./' + myString);
var obj = new MyClass();
console.log(obj.foo); // returns "bar"
One more reason why CommonJS is such a pleasure.
eval("javascript code");
it is extensively used when dealing with JSON.