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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With