microsoft / Chakra-Samples

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

Adding items to a JS array using CallFunction doesn't add #70

Open danpetitt opened 7 years ago

danpetitt commented 7 years ago

Trying to add items to a Javascript Array fails to add the item for some reason:

var jsTextToInsert = JavaScriptValue.FromString( "String to add to array" );

var arrayObject = JavaScriptValue.GlobalObject.GetProperty( JavaScriptPropertyId.FromString( "myArray") );
var pushFunctionObject = arrayObjectGetProperty( JavaScriptPropertyId.FromString( "push" ) );
var result = pushFunctionObject.CallFunction( JavaScriptValue.GlobalObject, jsTextToInsert );

var length = (int)arrayObject.GetProperty( JavaScriptPropertyId.FromString( "length" ) ).ToDouble();
Debug.Assert( length == 1 );

I can add items to the array using an alternative indexed property approach but it would be nice the 'push' function worked:

JavaScriptValue indexValue = JavaScriptValue.FromInt32( length );
arrayObject.SetIndexedProperty( indexValue, jsFileName );

Any ideas what I am doing wrong, or is this an issue; calling other functions works fine.

liminzhu commented 7 years ago

Hi @coderangerdan . Speaking in terms of JS, your code can be roughly translated to,

let arr = [];
let p = arr.push;
p.call(global, 'new string');
arr.length; // eval to 0 in JS

In this case you want arr to be the thisArg for call, or bind p to arr in the first place.