如何在ClearScript的V8ScriptEngine中使用含顶层this的脚本?
解决ClearScript V8中顶层
this未定义的问题 在ES模块模式(ModuleCategory.Standard)下,顶层this本身就是undefined,这是ES模块的规范行为。要让脚本识别顶层this,可以用以下几种方案:
方案1:切换到全局执行模式
将脚本的模块类别从ModuleCategory.Standard改为ModuleCategory.Global,此时脚本运行在传统全局环境中,顶层this会指向V8的全局对象(类似浏览器的window或Node.js的global)。
修改后的代码示例:
engine.Execute( new DocumentInfo() { Category = ModuleCategory.Global }, @" // Logger is a dotnet class that wraps Debug.Output. Logger.Write('isDef: ' + isDef(this)); // 现在会输出'true' function isDef(obj) { if(obj === undefined || obj === null) { return 'false'; } else { return 'true'; } } " );
方案2:在模块模式下polyfill顶层this
如果必须使用ModuleCategory.Standard模块模式,可以在脚本开头注入代码,将V8的全局对象(globalThis)绑定到顶层this变量上:
engine.Execute( new DocumentInfo() { Category = ModuleCategory.Standard }, @" // Polyfill顶层this指向全局对象 globalThis.this = globalThis; // Logger is a dotnet class that wraps Debug.Output. Logger.Write('isDef: ' + isDef(this)); // 现在会输出'true' function isDef(obj) { if(obj === undefined || obj === null) { return 'false'; } else { return 'true'; } } " );
或者也可以直接在调用用户脚本前单独执行polyfill代码:
// 先注入polyfill engine.Execute(new DocumentInfo() { Category = ModuleCategory.Standard }, "globalThis.this = globalThis;"); // 再执行目标脚本 engine.Execute( new DocumentInfo() { Category = ModuleCategory.Standard }, @" Logger.Write('isDef: ' + isDef(this)); function isDef(obj) { if(obj === undefined || obj === null) { return 'false'; } else { return 'true'; } } " );
方案3:直接使用globalThis替代this
如果脚本可以修改,直接用ES标准的globalThis代替顶层this,它在模块和全局模式下都能指向全局对象:
engine.Execute( new DocumentInfo() { Category = ModuleCategory.Standard }, @" Logger.Write('isDef: ' + isDef(globalThis)); // 输出'true' function isDef(obj) { if(obj === undefined || obj === null) { return 'false'; } else { return 'true'; } } " );
内容的提问来源于stack exchange,提问作者Mike Cheel
相关产品推荐
相关产品推荐

