如何通过名称调用命名空间下的回调函数?
问题解决:通过全限定函数名调用命名空间内的函数
首先纠正你代码里的一个笔误: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"
代码解释
- 拆分路径:用
split('.')把'ns.someFunc'拆成['ns', 'someFunc']数组。 - 逐层遍历:从
window开始,先取window['ns']得到命名空间对象,再取该对象的someFunc属性,最终拿到目标函数。 - 边界判断:遍历过程中如果遇到非对象的中间值(比如路径不存在),直接终止并标记为
undefined,避免报错。
内容的提问来源于stack exchange,提问作者Trebla
相关产品推荐
相关产品推荐

