Object Creation
QuickJS provides several functions to create JavaScript objects from C code.JS_NewObject
Create a new plain JavaScript object.Parameters
ctx- The JavaScript context
Returns
Returns a new empty object.Example
JS_NewObjectProto
Create a new object with a specific prototype.Parameters
ctx- The JavaScript contextproto- The prototype object (can beJS_NULLfor null prototype)
Returns
Returns a new object with the specified prototype.Example
JS_NewObjectClass
Create a new object instance of a custom class.Parameters
ctx- The JavaScript contextclass_id- The class ID of the object to create
Returns
Returns a new object of the specified class.Example
JS_NewObjectProtoClass
Create a new object with both a specific prototype and class.Parameters
ctx- The JavaScript contextproto- The prototype objectclass_id- The class ID
Returns
Returns a new object with the specified prototype and class.Example
Fromexamples/point.c:
JS_NewObjectFrom
Create an object from arrays of atoms and values.Parameters
ctx- The JavaScript contextcount- Number of propertiesprops- Array of property name atomsvalues- Array of property values (ownership transferred)
Returns
Returns a new object with the specified properties.JS_NewObjectFromStr
Create an object from arrays of string property names and values.Parameters
ctx- The JavaScript contextcount- Number of propertiesprops- Array of property name stringsvalues- Array of property values (ownership transferred)
Returns
Returns a new object with the specified properties.Example
JS_ToObject
Convert a value to an object.Parameters
ctx- The JavaScript contextval- The value to convert
Returns
Returns an object representation of the value, orJS_EXCEPTION on error.
Example
Notes
- All
JS_NewObject*functions return values that must be freed withJS_FreeValue() - For custom classes, use
JS_NewObjectClass()orJS_NewObjectProtoClass() JS_NewObjectFrom*functions take ownership of the values array- Use
JS_SetOpaque()to attach C data to class objects