microsoft / Chakra-Samples

Repository for Chakra JavaScript engine related samples.
MIT License
216 stars 84 forks source link

CallFunction seems to require extra argument which is not documented. #24

Closed zoryn closed 8 years ago

zoryn commented 8 years ago

I’m trying to use c# sample. I need to get the function from the script file and execute it with specific arguments. My script is

var f1= function foo(x, y) {
    return x + y;
}

My code is:

JavaScriptContext.RunScript(script);
var f1 = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("f1"));
var result = f1.CallFunction(JavaScriptValue.FromInt32(1), JavaScriptValue.FromInt32(2));

I expect code to return value of type number with value 3. It returns NaN instead.

I’ve spent quite a bit of time trying to understand this and it looks like CallFunction expects some additional argument. If I add any value (e.g. NULL as the first argument), everything works as expected. Is this how it is supposed to work? What is the meaning of this extra argument?

Note addition of JavaScriptValue.Null

JavaScriptContext.RunScript(script);
var f1 = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("f1"));
var result = f1.CallFunction(JavaScriptValue.Null, JavaScriptValue.FromInt32(1), JavaScriptValue.FromInt32(2));
SrinivasGourarum commented 8 years ago

Jscallfunction expects global object (https://msdn.microsoft.com/en-us/library/dn249675(v=vs.94).aspx) to be passed as the first argument in this case. I believe it is supposed to be the object which holds the function being called.

liminzhu commented 8 years ago

Think of it as Function.prototype.call, which requires a thisArg as a first argument.

zoryn commented 8 years ago

Thank you for the quick response!