问题
My question is sort of complex but I will try to word as best I can.
I am making a website with that involves a lot of javascript. I don't have everything setup so some of the scripts aren't hooked up with anything. I want to make a popup console that will allow me to type in what function I want the computer to preform and have the computer do so.
Can I have a variable and then call a function with that variable example:
var CodeApprentice = "Cat"; function Cat(){ document.write("kitten"); } function Dog(){ document.write("puppy"); } //Here is were I want to call the function with the variable CodeApprentice // and have it do the cat function function CodeApprentice();
I know I am not doing this correctly, but is there a way to do this or am I just crazy?
回答1:
You can access any property of an object in two ways either dot notation
obj.propertyName
or using the property name as a key
obj["propertyName"]
any function you define in the global name sapce will become part of the global object so in your case you can do
//this is meant as a to the global object other names might be appropriate
//such as window depending on the context
this[CodeApprentice]()
to execute the funciton Cat
writing
function Cat() {
}
is equivalent to
Cat = function(){
}
where the latter is more explicitly showing that it's actually a property of this
being set (I didn't say it's obvious just that it hides the fact less than the previous)
as a final note it's a general convention that functions that start with an upper case letter are constructors and should be called with the new key word e.g. new Cat()
since that's probably not what you want in this case you should think about renaming the function (if the actual code has functions starting with upper case letters)
回答2:
you can store all the available functions in an object
var availableFunctions {
cat: correspondingFunction
}
then you can get input as a string
var input = 'cat';
availableFunctions[input]();
回答3:
Use .call
or .apply
var codeApprentice = Cat;
codeApprentice.call(null);
You could have a cleaner solution with some better composition
// my_class.js
var MyClass = function() {};
MyClass.Cat = function() {
document.write("kitten");
};
MyClass.Dog = function() {
document.write("puppy");
};
// usage
var codeApprentice = "Cat";
MyClass[codeApprentice].call(null);
// => "kitten"
Here's a fiddle with some HTML controls
回答4:
you can do it like this and even pass parameters in it
var strFun = "Cat";
var strParam = "";
//Create the function
var fn = window[strFun];
//Call the function
fn(strParam);
Or you can do it using the eval()
function like this
var strFun = "Cat";
var strParam = "";
//Create the function call from function name and parameter.
var funcCall = strFun + "('" + strParam + "');";
//Call the function
var ret = eval(funcCall);
来源:https://stackoverflow.com/questions/17025891/how-to-call-a-function-by-a-variable-name