Reputation: 125
I want to create a function dynamically using javascript. I've started with the following:
function setFunc(setName){
var setName = function () {
};
}
setFunc("totop");
I want to set a function dynamically, but it doesn't work!
How can I fix this?
Upvotes: 3
Views: 10144
Reputation:
That won't work.
However, consider this: functions in JavaScript are just values and window is the top-level scope, so... (This assumes it is desired for the new function to be created in the top-level scope.)
function setFunc (name) {
window[name] = function () { alert("hi!") }
}
setFunc("a")
window.a() // "hi!" - explicit property access on object
window["a"]() // "hi!" - ditto
a() // "hi!" - window implicit as top-level
However, I do not recommend this sort of global side-effect...
Happy coding.
Upvotes: 6
Reputation: 27880
Don't Use the eval function like this:
function setFunc(setName){
eval (setName + " = function () { };");
}
setFunc("toTop");
You can access the window scope as an associative array and define the function with that name:
function setFunc (name) {
window[name] = function () { }
}
Upvotes: 1
Reputation: 235992
The question is, in which context you want to create that function. If you really want to create a global function with that name, do it like
function setFunc( setName ) {
this[ setName ] = function() {
alert('I am ' + setName);
};
}
setFunc('totop');
However, this is not a great idea to clobber the global object like that. Furthermore, the above code will break in es5 strict mode. However, by using the new
keyword, you could create constructs like
new setFunc('foobar').foobar();
or just store the result in a variable
var myObj = new setFunc('BoyohboyWhatALongString');
console.log( myObj ); // BoyohboyWhatALongString() is in there now
Upvotes: 5