ClearScript - scripts that refer to this

102 views Asked by At

How does one use scripts that refer to this (in the context of a top level window or global) in them? For example, the following uses the V8ScriptEngine to refer to this:

engine.Execute(
    new DocumentInfo() { Category = ModuleCategory.Standard },
    @"  
        //  Logger is a dotnet class that wraps Debug.Output. 
        Logger.Write('isDef: ' + isDef(this)); // logs 'false'
       
        function isDef(obj) {
            if(obj === undefined || obj === null) {
                return 'false';
            } else {
                return 'true';
            }
        }
    "
);

So far I have been unable to run scripts that refer to this. It is pretty common for scripts to refer to this (meaning as some sort of top level like window or global) so I am hoping I just missed something. I basically want to trick the script into thinking that this exists (via polifill, settings, etc).

1

There are 1 answers

3
BitCortex On

So far I have been unable to run scripts that refer to this.

As stated here (about half way down), this is always undefined at the top level of a module. You can use globalThis however.

It is pretty common for scripts to refer to this

AFAIK, that's true for normal scripts but not modules. Does your script have to run as a module?