Calling a javascript object's function from C#

Nov 30, 2014 at 5:58 PM
I've been a C++/C# programmer for many years but I'm very new to javascript and Jurassic, so sorry if this question may be a little remedial, but I couldn't seem to find the answer in documentation or forums. I would like to be able to create instances of a javascript object and call it's functions from C#. Something like so:
Jurassic.ScriptEngine scriptEngine = new Jurassic.ScriptEngine();
string testScript = "function myObject() { this.number = 10; this.test = function() { return this.number; } }";
object obj = scriptEngine.Evaluate(testScript);
 // call the test function
object ret = ((ObjectInstance)obj).CallMemberFunction("test", null);
I know that's not right, and I've seem some examples similar to what I want, but nothing that did exactly what I expect. This is of course a simple example.
Dec 1, 2014 at 12:09 AM
So, I've gotten this far:
Jurassic.ScriptEngine scriptEngine = new Jurassic.ScriptEngine();

string testScript = "function myObject(num) { this.number = num; this.test = function() { return \"Hello, I'm #\" + this.number; } }"; 

FunctionInstance obj = scriptEngine.GetGlobalValue("myObject") as FunctionInstance;

int[] parameters = new int[1];
parameters[0] = 1;

object func = obj.GetPropertyValue("test");
object ret = ((FunctionInstance)func).Call(obj, 0);
func is returning null, though, so I still can't call the function. Also, I'm not sure how to create a new instance of the object from c#. I was thinking I could use the FunctionInstance as a prototype to instantiate a new object, but I still haven't figured out how do do that.
Dec 1, 2014 at 8:26 PM
In C# terms you are trying to access an instance field without an instance. My guess is you are thinking that myObject (obj in the code above) is the instance, but it's not -- myObject is a function. To get an instance you need to do the equivalent of "new myObject(num)". In Jurassic this would be: obj.ConstructLateBound(num)

Then you can retrieve the "test" property of the resulting instance, and call that.