Reputation: 3185
I have the need to create a function from a name stored in a variable. Usually this is pretty simple, I've done it before using:
var funcName = "theName";
window[funcName] = function(){
// code here
};
However in my new usecase the function I create needs to sit inside an object called the.Name
. So what I tried to do, and it doesn't work is:
var funcName = "the.Name";
window[funcName] = function(){
// code here
};
The reason it doesn't work is because I can't reference window["the.Name"]
as that's invalid, the correct way is window["the"]["Name"]
.
Does anyone have a a solution for this problem? Basically naming a function which will sit inside an object when the name is stored in a variable.
Upvotes: 0
Views: 86
Reputation: 28124
OK, I seem to understand your problem.
Here's some code to get you started.
/**
* @param fn The function to bind.
* @param path The object to bind to.
* @param root The root object.
*/
function bindFunc(fn, path, root){
path = path.split('.');
var base = root;
for(var i=0; i<path.length-1; i++){
base = base[path[i]];
}
base[path[path.length - 1]] = fn;
}
bindFunc(function(){ }, 'the.Name', window);
Upvotes: 2
Reputation: 25322
If you're sure that all object till the last one exists (the last one could also not be defined), the shortest way probably is using reduce
var func = funcName.split(".").reduce(function(p, c) {
return p[c];
}, window);
Upvotes: 1
Reputation: 2484
I'm going to make a guess that you're trying to do something "namespace-like". Here's an article that should get you started (has some good example code, too)..
http://blogger.ziesemer.com/2008/05/javascript-namespace-function.html
Upvotes: 1
Reputation: 700312
Split the string so that you can reference one level at a time:
var names = funcname.split(".");
var f = window;
for (var i = 0; i < names.length - 1; i++) {
f = f[names[i]];
}
f[names[names.length - 1]] = function(){...};
Upvotes: 0