Search code examples
javascriptc#.netjscriptclearscript

Does Clearscript ScriptEngine retain code for subsequent Execute calls?


var sharedJSLibrary = "bla";
var specificDownstreamScript = "bla2";

scriptEngine.Execute(sharedJSLibrary);
scriptEngine.Execute(specificDownstreamScript);

Do the clearScript engines retain code for use in subsequent Execute calls? If not, is there another mechanism to use for establishing a base library without having to merge it into the specific downstream script?

For instance, the MSScriptControl system had an AddCode method that you could call multiple times to insert several separate scripts.


Solution

  • Do the clearScript engines retain code for use in subsequent Execute calls?

    Yes. Each engine manages a script execution environment, and if a script changes that environment in any way (e.g., by setting up a new global function, adding a property to an existing object, etc.), those changes are retained across calls.

    Example:

    const string plusLib = "function plus(x, y) { return x + y; }";
    const string minusLib = "function minus(x, y) { return x - y; }";
    engine.Execute(plusLib);
    engine.Execute(minusLib);
    Console.WriteLine(engine.Evaluate("plus(1, minus(2, 3))")); // output: "0"