【问题标题】:Use a string in a function, ReferenceError在函数中使用字符串,ReferenceError
【发布时间】:2020-01-16 10:59:23
【问题描述】:

我正在尝试将字符串用作函数的一部分。

const import1 = require('./import1');
const import2 = require('./import2');

//on above files there is a method, let's call it method1.

const string = "import1"; // or could be "import2"

//I would like to use above string as code.

//This is what I tried:

const functionToUse = new Function(string + ".method1()");
functionToUse();

这是我得到的错误:“ReferenceError: import1 is not defined”

我检查了这个答案:Convert a string to a function, gives ReferenceError,它有点工作,但我需要将 import1 或 2 作为字符串传递。

非常感谢所有帮助!

【问题讨论】:

  • 代替new Function,创建一个FunctionMap,然后使用key访问
  • 问题是,您正在尝试创建一个类似的函数:new Function('obj.method1()') 并且这样的属性不存在。快速破解将使用eval,但不建议这样做。而是做const fnMap = { import1, import2 }; const obj = fnMap[string]; obj.method1();
  • 与几乎所有“如何将字符串转换为变量”问题一样,与之相对的是“您必须避免使用对象的具体原因是什么?”
  • @Rajesh 这真是太神奇了,我没想到这一点。非常感谢!!!您能否为此创建一个答案,然后我可以接受。

标签: javascript node.js function


【解决方案1】:

为什么不使用对象来访问函数?

const import1 = { method: function() { alert('method!'); } }; //require('./import1');
const import2 = { method2: function() {alert('method2'); } }; // require('./import2');


// Add link to both objects

window.myImports = { import1, import2 };
const string = "import1";
const functionToUse = getFunction(string + ".method");

function getFunction(path) {
  const parts = path.split('.');
  let obj = window.myImports;
  
  for(let part of parts) {
    obj = obj[part];
  }
  
  return obj;
}

functionToUse();

【讨论】:

    【解决方案2】:

    您的导入语句有问题。否则函数调用没有问题。

    let string1 = "hello";
    var functionCalls = (string)=>{ 
    	console.log("string inside function", string);
    }
    functionCalls(string1);

    您可以查看示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2012-10-22
      相关资源
      最近更新 更多