如何通过变量名调用函数 [英] How to call a function by a variable name

查看:34
本文介绍了如何通过变量名调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题有点复杂,但我会尽我所能.

My question is sort of complex but I will try to word as best I can.

我正在制作一个涉及大量 javascript 的网站.我没有设置所有内容,因此某些脚本没有与任何内容相关联.我想制作一个弹出式控制台,允许我输入我希望计算机执行的功能并让计算机执行.

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.

  1. 我可以有一个变量,然后使用该变量调用函数吗?示例:

  1. 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?

推荐答案

您可以通过两种方式访问​​对象的任何属性,即点表示法

You can access any property of an object in two ways either dot notation

obj.propertyName

或使用属性名称作为键

obj["propertyName"]

您在全局名称 sapce 中定义的任何函数都将成为全局对象的一部分,因此您可以这样做

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]()

执行函数Cat

写作

function Cat() {
}

相当于

Cat = function(){
}

后者更明确地表明它实际上是this被设置的一个属性(我没有说这很明显,只是它比前一个隐藏的事实更少)

where the latter is more explicitly showing that it's actually a property of thisbeing set (I didn't say it's obvious just that it hides the fact less than the previous)

最后要注意的是,以大写字母开头的函数是构造函数,应使用新关键字调用,这是一个通用约定,例如new Cat() 因为在这种情况下这可能不是您想要的,所以您应该考虑重命名函数(如果实际代码具有以大写字母开头的函数)

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)

这篇关于如何通过变量名调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆