Class inheritance

May 22, 2011 at 4:47 PM
Edited May 22, 2011 at 4:54 PM

Hello, I've recently found out about, 'Jint'. I would like to have some pointers about this problem and answers if it's even possible to do!

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Jint;
using Jint.Delegates;

namespace Javascript
{
    public class Base
    {
        public int square(int a, int b)
        {
            return a * b;
        }
    }

    class Program
    {        
        static void Main(string[] args)
        {
            var jint = new JintEngine().DisableSecurity();
            var script = new StreamReader(@"scripts\test.js").ReadToEnd();

            jint.SetFunction("print", new Action<object>(Console.WriteLine));

            jint.Run(script);

            Console.ReadKey();
        }
    }
}

 

--

 

function Extended() {
    this.add = function (a, b) {
        return a + b;
    }
}

var base = new Javascript.Base();

Extended.prototype = base;

var i = new Extended();

print(i.add(2, 2));
print(i.square(2, 4));
print(base.square(4, 4));

 

--

edit: the line 'print(i.square(2, 4));' is where the error appear, the method isn't found.

Thanks in advance!

Regards, F.

Developer
May 22, 2011 at 9:19 PM

Are you sure about the text of the the exception, since I tried your example, and got another one.

May 22, 2011 at 11:27 PM
cin wrote:

Are you sure about the text of the the exception, since I tried your example, and got another one.

Ah, you're right.

"The specified 'that' object is not acceptable for this method"

Could still use some help to interpretate that.

Regards, F.

Developer
May 23, 2011 at 9:07 PM

This is because the object you created with constructor 'Extended' doesn't hold a CLR instance.

you should add a call to the base class constructor as shown below

function Extend() {
    Javascript.Base.call(this); // call a base class constrictor

    // your initialization code here
}

this is a class inheritance approach, however an object inheritance approach isn't supported yet due to some complexity of the iteroperation implementation (which may seriously affect performance).

All native constructors are marshalled as functions and applying a such constructor to the object will lead to creation of a new CLR instance and associating it with the script object. After this the script object can be used as a CLR object.

Please note that this feature is highly experimental and there can be some bugs in it.