This project has moved. For the latest updates, please go here.

Calling method on type

Jan 1, 2015 at 4:01 AM
I have the following JS:

(function(algo) {
""use strict"";

var context = algo.context;

algo.init = function() {
    context.i = 0;
};

algo.onBars = function(bars) {
    context.i++;
};
})(algorithm);

I then want to do something like this:

_engine.Execute("var algorithm = {context: {}};");
_engine.Execute(scriptPackage.
_engine.CallGlobalFunction("algorithm.init");

But it does not quite work, I know I can do _engine.Execute("algorithm.init()"); but I might need to pass some parameters through which is a .net collection, Any way to get this working?



Thanks
Jan 1, 2015 at 4:07 AM
I also notice a fairly big performance difference between calling .Execute("foo()") and CallGlobalFunction("foo"), the latter being much faster, is this expected?


Thanks
Coordinator
Jan 2, 2015 at 7:37 AM
Edited Jan 2, 2015 at 7:41 AM
How about something like this? (note: untested, please forgive typos)
// Create new global variable called "algorithm".
var algorithm = _engine.Object.Construct();
algorithm["context"] = _engine.Object.Construct();
_engine.SetGlobalValue("algorithm", algorithm);

// Then execute your script.
_engine.Execute(script);

// Then call algorithm.init with algorithm as the "this" parameter.
((FunctionInstance)algorithm["init"]).CallLateBound(algorithm);
I also notice a fairly big performance difference between calling .Execute("foo()") and CallGlobalFunction("foo"), the latter being much faster, is this expected?
Yes. Execute requires compilation, which ends up creating an in-memory dynamic assembly and then calling into it. The overhead is large and you should avoid using it where possible.