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

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

问题描述

我有一个包含JavaScript函数名称的JavaScript变量。这个函数存在于页面中,通过使用$ .ajax等进行加载和放置。



任何人都可以告诉我如何调用变量中指定的javascript函数,请吗?

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



我接受其他关于如何实现这个解决方案的建议。

解决方案



为了解决这个问题,你应该知道关于JavaScript的这些东西。


  1. 函数是第一类对象,所以它们可以是对象的属性(在这种情况下称为方法),甚至可以是数组的元素。

  2. 如果您未选择函数所属的对象,则它属于全局范围。在浏览器中,这意味着你将它挂在名为window的对象上,这是全局变量的存在位置。

  3. 数组和对象密切相关。 (谣言是它们甚至可能是乱伦的结果!)你通常可以用点 来代替方括号 [] ,反之亦然。 您的问题是一个结果考虑点引用的方式而不是方括号的方式。



    那么,为什么不能像这样,

     窗口[ functionName](); 

    假设您的函数存在于全局空间中。如果你有命名空间,那么:

      myNameSpace [functionName](); 

    避免使用eval,并避免将字符串传入setTimeout和setInterval。我写了很多JS,我从不需要评估。 需要评估来自于不够深入地了解语言。您需要了解范围,上下文和语法。如果你一直坚持评估,只需问 - 你会很快学会。


    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.

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

    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.

    解决方案

    I'd avoid eval.

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

    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.

    So, why not something like,

    window["functionName"]();
    

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

    myNameSpace["functionName"]();
    

    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天全站免登陆