V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Alander
V2EX  ›  程序员

webpack tabable 为什么选择实时 generateCode?

  •  
  •   Alander · 2021-12-10 11:51:52 +08:00 · 644 次点击
    这是一个创建于 885 天前的主题,其中的信息可能已经有所发展或是发生改变。

    tabable 中的各种 hook 最终被 call 的时候,会通过 new Function(args, codeContent) 的形式生成一个函数

    我好奇的是为什么它一定要用这种方式?例如:

    case "sync":
    				if (!rethrowIfPossible) {
    					code += `var _hasError${tapIndex} = false;\n`;
    					code += "try {\n";
    				}
    				if (onResult) {
    					code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
    						before: tap.context ? "_context" : undefined
    					})});\n`;
    				} else {
    					code += `_fn${tapIndex}(${this.args({
    						before: tap.context ? "_context" : undefined
    					})});\n`;
    				}
    				if (!rethrowIfPossible) {
    					code += "} catch(_err) {\n";
    					code += `_hasError${tapIndex} = true;\n`;
    					code += onError("_err");
    					code += "}\n";
    					code += `if(!_hasError${tapIndex}) {\n`;
    				}
    				if (onResult) {
    					code += onResult(`_result${tapIndex}`);
    				}
    				if (onDone) {
    					code += onDone();
    				}
    				if (!rethrowIfPossible) {
    					code += "}\n";
    				}
    				break;
    

    可以看见是通过字符串生成 code 内容。

    那为什么不直接将 callTap 的方法写死呢?

    function call(...args) {
      for (let tap of tapArr) {
        tap.fn.apply(null, args);
      }
    }
    

    这样不行吗?两者有什么区别? tabable 选择上面那种事为了解决什么问题呢?有大佬提个醒吗?

    1 条回复    2021-12-10 23:51:12 +08:00
    Opportunity
        1
    Opportunity  
       2021-12-10 23:51:12 +08:00
    Eval function ,经典性能榨汁机

    比如这个也是
    https://www.zhihu.com/question/276403215/answer/386917514
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1031 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:07 · PVG 04:07 · LAX 13:07 · JFK 16:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.