Re-using script object

Dec 19, 2013 at 7:18 PM
Hi,

I'm using a library (CSG.js) and I need to call it from .Net. I instantiate a few objects and do operation on them. The information on what object and how I combine them comes from .Net. I'm having problem figuring how to do this.

I'm getting this error: 'Microsoft.ClearScript.Undefined' does not contain a definition for 'DoStuff'

Here's a simplified sample of what I'm doing.
        V8ScriptEngine engine;

        engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging);

        engine.Execute(@"MyClass = function() {
                                this.First = [];
                                this.Second = 2;
                            };

                            MyClass.prototype = {
                                DoStuff: function(someInt) {
                                    var mc = new MyClass();
                                    mc.Second = this.Second + mc.Second;
                                }
                            };
                            ");

        dynamic v1 = engine.Evaluate("new MyClass();");

        dynamic v2 = engine.Evaluate("new MyClass();");

        dynamic res = engine.Script.v1.DoStuff(2);

        Console.WriteLine((int)res);
Thanks
Coordinator
Dec 19, 2013 at 8:47 PM
Edited Dec 19, 2013 at 9:13 PM
Hi ssylvain,

First, you probably need to add a return statement to DoStuff; otherwise it returns undefined.

Next, you're getting the error because v1 is a .NET variable, but engine.Script.v1 tries to retrieve a nonexistent global property named "v1" from the script engine.

You probably either want to do something like this:
dynamic v1 = engine.Evaluate("new MyClass()");
var res1 = Convert.ToInt32(v1.DoStuff(2));
Console.WriteLine(res1);
or something like this:
engine.Execute("v2 = new MyClass()");
var res2 = Convert.ToInt32(engine.Evaluate("v2.DoStuff(2)"));
Console.WriteLine(res2);
Cheers!