[TIPS] How To Properly Call A Method

Jan 14, 2012 at 7:46 PM
Edited Jan 14, 2012 at 7:51 PM

Imports:

using System;
using Jint;
using Jint.Native;

In Program:

static JintEngine e = new JintEngine();

static void Main(string[] args)
{
    try
    {
        // This doesn't work
        e.SetFunction("foo", new Foo(FooImpl));
        e.Run(@"
            foo({
                foo: 'Hello world!',
                bar: function() {
                    return this.foo
                }
            })
        ");
    }
    catch (Exception)
    {
        /**
         * Throws:
         *   Object reference not set to an instance of an object.
         *   Line: 5 Char: 20
         *   No source code available.
         */
    }

    // This does work
    e.Run(@"
        function __call(obj, fn) {
            return fn.call(obj);
        }
    ");
    e.SetFunction("foo2", new Foo2(Foo2Impl));
    e.Run(@"
        foo2({
            foo: 'Hello world!',
            bar: function() {
                return this.foo
            }
        })
    ");

    Console.Read();
}

delegate void Foo(JsObject o);

static void FooImpl(JsObject o)
{
    Console.WriteLine("o.foo = " + o["foo"]);
    Console.WriteLine("o.bar = " + e.CallFunction((JsFunction)o["bar"], new object[] { }).ToString());
}

delegate void Foo2(JsObject o);

static void Foo2Impl(JsObject o)
{
    Console.WriteLine("o.foo = " + o["foo"]);
    Console.WriteLine("o.bar = " + e.CallFunction("__call", o, o["bar"]));
}

Hope this short code dump useful somehow...

Thanks for writing this awesome library :D

Jan 14, 2012 at 9:27 PM

This is interesting! Thank you.