调用以变量命名的 JavaScript 函数 [英] Calling a JavaScript function named in a variable

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

问题描述

我有一个 JavaScript 变量,其中包含一个 JavaScript 函数的名称.该函数通过使用$.ajax 等加载并放置在页面上.

I have a JavaScript variable which contains the name of a JavaScript function. This function exists on the page by having been loaded in and placed using $.ajax, etc.

谁能告诉我如何调用变量中命名的 javascript 函数?

Can anyone tell me how I would call the javascript function named in the variable, please?

函数的名称在一个变量中,因为用于加载页面片段(被插入到当前页面)的 URL 包含要调用的函数的名称.

The name of the function is in a variable because the URL used to load the page fragment (which gets inserted into the current page) contains the name of the function to call.

我愿意接受有关如何实施此解决方案的其他建议.

I am open to other suggestions on how to implement this solution.

推荐答案

我会避免使用 eval.

I'd avoid eval.

要解决这个问题,你应该了解 JavaScript 的这些东西.

To solve this problem, you should know these things about JavaScript.

  1. 函数是一等对象,因此它们可以是对象的属性(在这种情况下,它们被称为方法),甚至是数组的元素.
  2. 如果您没有选择函数所属的对象,则它属于全局作用域.在浏览器中,这意味着您将它挂在名为window"的对象上,这是全局变量所在的位置.
  3. 数组和对象密切相关.(有传言说它们甚至可能是乱伦的结果!)您通常可以使用点 . 代替方括号 [],反之亦然.
  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

您的问题是考虑了点引用方式而不是方括号方式的结果.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

所以,为什么不喜欢,

window["functionName"]();

假设您的函数存在于全局空间中.如果您已命名空间,则:

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

避免使用 eval,并避免将字符串传入 setTimeout 和 setInterval.我写了很多 JS,我从不需要 eval.需要" eval 来自对语言的了解不够深入.您需要了解范围、上下文和语法.如果您对 eval 感到困惑,只需询问即可——您会很快学会.

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

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

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