You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过名称调用命名空间下的回调函数?

问题解决:通过全限定函数名调用命名空间内的函数

首先纠正你代码里的一个笔误:theCaller函数里的callbackFunctionName应该替换成参数funcName,不然第一个调用也会报错。

核心问题在于,当你传入'ns.someFunc'时,window['ns.someFunc']是在找window对象中**键名完全等于ns.someFunc**的属性,但实际window里只有ns这个属性,someFunc是ns对象的属性,所以直接用字符串索引找不到。

要解决这个问题,需要把全限定函数名按.拆分,逐层遍历对象:

var ns = {
    someFunc: function() { console.log('stuff'); }
}

function someTopLevelFunc() { console.log('top level'); }

function theCaller(funcName) {
  console.log("Callback name: " + funcName);
  // 拆分路径,逐层查找函数
  let current = window;
  const pathSegments = funcName.split('.');
  
  for (const segment of pathSegments) {
    if (!current || typeof current !== 'object') {
      current = undefined;
      break;
    }
    current = current[segment];
  }

  console.log("Type: " + (typeof current));

  if (typeof current === "function") {
     current.apply(null, []);
  }
}

theCaller('topLevelFunc'); // 输出 "top level"
theCaller('ns.someFunc'); // 输出 "stuff"

代码解释

  1. 拆分路径:用split('.')把'ns.someFunc'拆成['ns', 'someFunc']数组。
  2. 逐层遍历:从window开始,先取window['ns']得到命名空间对象,再取该对象的someFunc属性,最终拿到目标函数。
  3. 边界判断:遍历过程中如果遇到非对象的中间值(比如路径不存在),直接终止并标记为undefined,避免报错。

内容的提问来源于stack exchange,提问作者Trebla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:55:15