Search code examples
c#javascript.net

Adding a global method in Javascript.net


I am working on a project that uses Javascript.net (formerly Noesis Javascript .net) as a scripting engine.

How do you add a C# method to the global context in Javascript? For example, say I have in C#:

public int Foo(int bar)
{
    return bar * 2;
}

I want to be able to call in Javascript:

var x = 5;
var y = Foo(x); // y is now 10;

In other libraries such as Jurassic this is possible:

 engine.SetGlobalFunction("Foo", new Func<int, int>((a) => a*2));

Solution

  • This example comes from the unit tests:

    _context.SetParameter("f", new Func<string,string>((s) => s.ToUpper()));
    _context.Run("f('Noesis') == 'NOESIS'").Should().BeOfType<bool>().Which.Should().BeTrue();