bellard / quickjs

Public repository of the QuickJS Javascript Engine.
https://bellard.org/quickjs
Other
8.52k stars 892 forks source link

Get/Set property of object passed as an argument #332

Closed jockm closed 4 months ago

jockm commented 4 months ago

Forgive me if this is in the documentation, but I couldn't seem to find it. Imaging I have the following Javascript:

let foo = {
    a: 1,
   b:  2
}

and I want to call a native function called MyCFunction that takes foo as an argument, reads a and b, adds them together, and then puts the result into result, such that foo would now be:

{
    a: 1,
    b:  2,
    result: 3
}

How do I:

  1. verify that the argument is a javascript object
  2. get the properties
  3. set a new property

Any guidance would be appreciated

saghul commented 4 months ago

For 1) you can use JS_IsObject, but you probably don't need to do that and go straight for checking for properties.

You can do that with JS_GetPropertyStr like so: `JSValue prop = JS_GetPropertyStr(ctx, obj, "a");

Setting a new property can be done like so: JS_SetPropertyStr(ctx, obj, "result", JS_NewInt32(ctx, 3)

jockm commented 4 months ago

@saghul Thank you so very much!