首页 > 解决方案 > JavaScript 给定的字符串是否作为变量和函数存在

问题描述

我有一个变量,它有一个成员变量,它是一个函数

let test = {
 setup: function() { ...}
}

从其他来源,我得到字符串“test.setup”

我如何检查是否

a.) 变量测试存在

b.) 变量 test 有一个名为 setup 的子项

c.) 子设置是一个函数?

d.) 调用函数

我已经测试过了

let variableName = "test.setup";

window[variableName] 
// undefined

{}.toString.call(variableName ) === '[object Function]' 
// VM2052:1 Uncaught SyntaxError: Unexpected token .

window.hasOwnProperty("test")
// false

如果你能解决我的问题,那就太好了。对我来说,看看是否有这样的函数并在它存在时调用它就足够了。否则通知用户没有这样的功能。

非常感谢您提前

标签: javascript

解决方案


简单但不太安全的方法是使用eval(). 永远不要使用eval()用户生成的数据,因为它是一种攻击媒介。

let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";

如果在未定义的变量上评估“.setup”,您将收到错误消息。所以你可以try/catch用来处理这个。

function exists(value) {
      try {
          return eval(value);
      } catch(e) {
          return undefined;
      }
}

console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined

推荐阅读