【问题标题】:JavaScript Determine if dynamically named function existsJavaScript 判断动态命名函数是否存在
【发布时间】:2011-05-01 13:35:58
【问题描述】:

如何检查动态命名的对象或函数是否存在?

例如:

var str = 'test';
var obj_str = 'Page_'+str;

function Page_test(){

}

if(typeof obj_str() == 'function') alert('ok');
else alert('error');

那我怎样才能调用对象呢?

例如:

var tst = obj_str();

【问题讨论】:

  • 当您基于页面特定的任何内容(例如标题或 URL)调用函数时,您引用的是 动态 函数、字符串或对象。当某些表单虽然不是所有表单都需要验证时,这是一种进行诸如主观表单验证之类的好方法。

标签: javascript


【解决方案1】:

您可以通过编写window[obj_str] 来获取全局名称。

Demo.

【讨论】:

  • 如果对象存在.. 我该如何使用它?叫它?
  • 写信window[obj_str]。例如:var result = window[obj_str]();.
  • 这里我得到'未定义'... var Obj = window['Page_test'];警报(Obj());
  • @clarkk:那是因为你的函数没有返回任何东西。
  • 它确实返回了一些东西.. "Obj is not defined"
【解决方案2】:

你很亲密,但不要尝试调用obj_str(它只是一个字符串,不可调用);相反,使用它来查找window 上的属性(因为所有全局函数和全局变量都是window 的属性):

if(typeof window[obj_str] == 'function') alert('ok');
//               ^-- No (), and use `window`
else alert('error');

如果你不关心它是一个具体的函数

if (obj_str in window) alert('ok');
else alert('error');

in 运算符检查给定字符串是否与给定对象中的属性名称匹配(在这种情况下,如果obj_str 的内容是window 中的属性)。

【讨论】:

    【解决方案3】:

    你的例子是对的,只是把obj_str()后面的括号去掉:

    if(typeof obj_str != 'undefined') alert('ok');
    else alert('error');
    

    这比window[obj_str] 更正确一点,因为 obj_str 可以定义在本地闭包中,或者如果您有嵌套闭包,则可以在包含闭包中定义,但不在窗口本身中。

    【讨论】:

      【解决方案4】:

      如果您在浏览器中运行代码,只需通过window 访问全局对象,您的代码可能是这样的:

      if (typeof window[obj_str] === 'string') {
          alert('ok');
      }
      

      否则,您应该可以访问全局对象:

      var global = function() { return this; }() || (1,eval)('this');
      if (typeof global[obj_str] === 'stribg
      

      【讨论】:

        猜你喜欢
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        • 2020-08-07
        • 2017-08-16
        相关资源
        最近更新 更多