Struct JSObject

Source
pub struct JSObject { /* private fields */ }
Expand description

A JavaScript object.

An JSObject is a JSValue. This is implemented by having JSObject implement the Deref trait so that anything that expects a JSValue can receive a JSObject as well.

Implementations§

Source§

impl JSObject

Source

pub const unsafe fn from_raw(ctx: JSContextRef, raw: JSObjectRef) -> Self

Create a new Self from its raw pointer directly.

§Safety

Ensure raw is valid.

Source

pub fn property_names(&self) -> JSObjectPropertyNameIter

Gets an iterator over the names of an object’s enumerable properties.

let ctx = JSContext::default();
let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
let o = v.as_object().expect("object");

let names: Vec<String> = o.property_names()
                          .map(|s| s.to_string())
                          .collect();
assert_eq!(names, vec!["id"]);
Source

pub fn has_property<S>(&self, name: S) -> bool
where S: Into<JSString>,

Tests whether an object has a given property.

  • name: A value that can be converted to a JSString containing the property’s name.

Returns true if the object has a property whose name matches name, otherwise false.

let ctx = JSContext::default();
let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
let o = v.as_object().expect("object");

assert!(o.has_property("id"));
Source

pub fn get_property<S>(&self, name: S) -> JSValue
where S: Into<JSString>,

Gets a property from an object.

  • name: A value that can be converted to a JSString containing the property’s name.

Returns the property’s value if object has the property, otherwise the undefined value.

let ctx = JSContext::default();
let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
let o = v.as_object().expect("object");

let n = o.get_property("id");
assert!(n.is_number());
// Remember that this will be an f64 now!
assert_eq!(n.as_number().expect("number"), 123.0);
§See also
Source

pub fn get_property_at_index(&self, index: u32) -> JSValue

Gets a property from an object by numeric index.

  • index: An integer value that is the property’s name.

Returns the property’s value if object has the property, otherwise the undefined value.

Calling get_property_at_index is equivalent to calling get_property with a string containing index, but get_property_at_index provides optimized access to numeric properties.

let ctx = JSContext::default();
let v = JSValue::new_from_json(&ctx, "[3, true, \"abc\"]").expect("valid array");
let o = v.as_object().expect("object");

let n = o.get_property_at_index(0).as_number().expect("number");
let b = o.get_property_at_index(1).as_boolean();
let s = o.get_property_at_index(2).as_string().expect("string");

assert_eq!(n, 3.0);
assert_eq!(b, true);
assert_eq!(s, "abc");

This also works with objects when the keys are strings of numeric indexes:

let ctx = JSContext::default();
let v = JSValue::new_from_json(&ctx, "{\"a\": 3, \"1\": true, \"2\": \"abc\"}").expect("valid object");
let o = v.as_object().expect("object");

// There is no property "0", so this will be `undefined`:
assert!(o.get_property_at_index(0).is_undefined());
assert_eq!(o.get_property_at_index(1).as_boolean(), true);
assert_eq!(o.get_property_at_index(2).as_string().expect("string"), "abc");
§See also
Source

pub fn set_property<S>( &self, name: S, value: JSValue, ) -> Result<(), JSException>
where S: Into<JSString>,

Set a property onto an object.

This can be used to create a new property, or to update an existing property.

  • index: A value that can be converted to a JSString containing the property’s name.
  • value: A value containing the property’s value.

Calling get_property_at_index is equivalent to calling get_property with a string containing index, but get_property_at_index provides optimized access to numeric properties.

let ctx = JSContext::default();
let object = JSValue::new_from_json(&ctx, r#"{"a": 10}"#).expect("valid object").as_object().unwrap();
object.set_property("b", JSValue::new_number(&ctx, 11.)).unwrap();

assert!(object.has_property("a"));
assert!(object.has_property("b"));
§See also
Source

pub fn set_property_at_index( &self, index: u32, value: JSValue, ) -> Result<(), JSException>

Set a property onto an object by using a numeric index.

This can be used to create a new property, or to update an existing property.

  • index: An integer value that is the property’s name.
  • value: A value containing the property’s value.

Calling set_property_at_index is equivalent to calling set_property with a string containing index, but set_property_at_index provides optimized access to numeric properties.

let ctx = JSContext::default();
let object = JSValue::new_from_json(&ctx, r#"[10]"#).expect("valid array").as_object().unwrap();
object.set_property_at_index(1, JSValue::new_number(&ctx, 11.)).unwrap();

assert!(object.has_property("0"));
assert!(object.has_property("1"));
§See also
Source

pub fn is_constructor(&self) -> bool

Returns true if the object can be called as a constructor, otherwise false.

let ctx = JSContext::default();
let global = ctx.global_object().unwrap();

let number = global.get_property("Number").as_object().unwrap();
assert!(number.is_constructor());

let math = global.get_property("Math").as_object().unwrap();
let pow = math.get_property("pow").as_object().unwrap();
assert!(!pow.is_constructor());
§See also
Source

pub fn call_as_constructor( &self, arguments: &[JSValue], ) -> Result<JSValue, JSException>

Call this object considering it is a valid object constructor.

let ctx = JSContext::default();
let global = ctx.global_object().unwrap();
let number = global.get_property("Number").as_object().unwrap();

let result = number.call_as_constructor(&[JSValue::new_string(&ctx, "42")]).unwrap();

assert!(result.is_object());
assert_eq!(result.as_number().unwrap(), 42.);
§See also
Source

pub fn is_function(&self) -> bool

Returns true if the object can be called as a constructor, otherwise false.

let ctx = JSContext::default();
let global = ctx.global_object().unwrap();

let number = global.get_property("Number").as_object().unwrap();
assert!(number.is_function());

let math = global.get_property("Math").as_object().unwrap();
let pow = math.get_property("pow").as_object().unwrap();
assert!(pow.is_function());

let pi = math.get_property("PI").as_object().unwrap();
assert!(!pi.is_function());
§See also
Source

pub fn call_as_function( &self, this: Option<&JSObject>, arguments: &[JSValue], ) -> Result<JSValue, JSException>

Call this object considering it is a valid function.

let ctx = JSContext::default();
let global = ctx.global_object().unwrap();
let math = global.get_property("Math").as_object().unwrap();
let pow = math.get_property("pow").as_object().unwrap();

let result = pow.call_as_function(
    None,
    &[JSValue::new_number(&ctx, 2.), JSValue::new_number(&ctx, 3.)],
).unwrap();

assert_eq!(result.as_number().unwrap(), 8.);
§See also

Methods from Deref<Target = JSValue>§

Source

pub fn to_json_string(&self, indent: u32) -> Result<JSString, JSException>

Creates a JavaScript string containing the JSON serialized representation of a JS value.

  • indent: The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.

Returns either a JSString with the result of serialization, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_boolean(&ctx, false);
let s = v.to_json_string(0).unwrap();
assert_eq!(s, "false");
Source

pub fn get_type(&self) -> JSType

Returns a JavaScript value’s type.

Returns a value of type JSType that identifies value’s type.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "true").expect("value");
assert_eq!(v.get_type(), JSType::Boolean);

let v = JSValue::new_from_json(&ctx, "5.0").expect("value");
assert_eq!(v.get_type(), JSType::Number);

let v = JSValue::new_from_json(&ctx, "null").expect("value");
assert_eq!(v.get_type(), JSType::Null);
Source

pub fn is_undefined(&self) -> bool

Tests whether a JavaScript value’s type is the undefined type.

Returns true if value’s type is the undefined type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_undefined(&ctx);
assert!(v.is_undefined());
§See also
Source

pub fn is_null(&self) -> bool

Tests whether a JavaScript value’s type is the null type.

Returns true if value’s type is the null type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "null").expect("value");
assert!(v.is_null());
§See also
Source

pub fn is_boolean(&self) -> bool

Tests whether a JavaScript value’s type is the boolean type.

Returns true if value’s type is the boolean type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "false").expect("value");
assert!(v.is_boolean());
§See also
Source

pub fn is_number(&self) -> bool

Tests whether a JavaScript value’s type is the number type.

Returns true if value’s type is the number type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "-23").expect("value");
assert!(v.is_number());
§See also
Source

pub fn is_string(&self) -> bool

Tests whether a JavaScript value’s type is the string type.

Returns true if value’s type is the string type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "\"Pueri et puellae\"").expect("value");
assert!(v.is_string());
§See also
Source

pub fn is_symbol(&self) -> bool

Tests whether a JavaScript value’s type is the symbol type.

Returns true if value’s type is the symbol type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_symbol(&ctx, "abc");
assert!(v.is_symbol());
§See also
Source

pub fn is_object(&self) -> bool

Tests whether a JavaScript value’s type is the object type.

Returns true if value’s type is the object type, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
assert!(v.is_object());
§See also
Source

pub fn is_object_of_class(&self, js_class: &JSClass) -> bool

Tests whether a JavaScript value is an object with a given class in its class chain.

  • js_class: The JSClass to test against.

Returns true if value is an object and has jsClass in its class chain, otherwise false.

§See also
Source

pub fn is_array(&self) -> bool

Tests whether a JavaScript value is an array.

Returns true if value is an array, otherwise false.

let ctx = JSContext::default();

let v = JSValue::new_array(&ctx, &[JSValue::new_number(&ctx, 123.), JSValue::new_number(&ctx, 456.)]).unwrap();
assert!(v.is_array());

// But an object is not an array.
let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
assert!(!v.is_array());
Source

pub fn is_typed_array(&self) -> bool

Tests whether a JavaScript value is a Typed Array.

let ctx = JSContext::default();

let value = JSValue::new_number(&ctx, 123.);
assert!(!value.is_typed_array());

let mut bytes = vec![1u8, 2, 3, 4, 5];
let value = unsafe {
    JSValue::new_typed_array_with_bytes(&ctx, bytes.as_mut_slice())
        .unwrap()
};
assert!(value.is_typed_array());
§See also
Source

pub fn is_date(&self) -> bool

Tests whether a JavaScript value is a date.

Returns true if value is a date, otherwise false.

Source

pub fn as_boolean(&self) -> bool

Converts a JavaScript value to boolean and returns the resulting boolean.

Returns the boolean result of conversion.

let ctx = JSContext::default();

let v = JSValue::new_boolean(&ctx, false);
assert_eq!(v.as_boolean(), false);
§See also
Source

pub fn as_number(&self) -> Result<f64, JSException>

Converts a JavaScript value to number and returns the resulting number.

Returns either the numeric result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_number(&ctx, 5.0);
let n = v.as_number().expect("valid number");
assert_eq!(n, 5.0);
§See also
Source

pub fn as_string(&self) -> Result<JSString, JSException>

Converts a JavaScript value to string and copies the result into a JavaScript string.

Returns either JSString with the result of conversion, or an exception if one was thrown. Ownership follows the Create Rule.

let ctx = JSContext::default();

let v = JSValue::new_string(&ctx, "Cave canem.");
let s = v.as_string().expect("valid string");
assert_eq!(s, "Cave canem.");
§See also
Source

pub fn as_object(&self) -> Result<JSObject, JSException>

Converts a JavaScript value to object and returns the resulting object.

Returns either the JSObject result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();

let v = JSValue::new_from_json(&ctx, "{\"id\": 123}").expect("valid object");
let o = v.as_object().expect("object");
// We now have an object that we can inspect.
§See also
Source

pub fn as_typed_array(&self) -> Result<JSTypedArray, JSException>

Converts a JavaScript value to a Typed Array object and returns the resulting object.

Returns either the JSTypedArray result of conversion, or an exception if one was thrown.

let ctx = JSContext::default();
let array = evaluate_script(
    &ctx,
    "new Uint8Array([1, 2, 3, 4, 5])",
    None,
    "foo.js",
    1,
).unwrap();

assert!(array.is_typed_array());

let array = array.as_typed_array().unwrap();
§See also
Source

pub fn protect(&self)

Protects a JavaScript value from garbage collection.

Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.

A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.

§See also
Source

pub fn unprotect(&self)

Unprotects a JavaScript value from garbage collection.

A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.

§See also

Trait Implementations§

Source§

impl Deref for JSObject

A JSObject can be dereferenced to return the underlying JSValue.

This lets a JSObject instance be used where a JSValue instance is expected.

Source§

type Target = JSValue

The resulting type after dereferencing.
Source§

fn deref(&self) -> &JSValue

Dereferences the value.
Source§

impl From<&JSObject> for JSValue

Source§

fn from(object: &JSObject) -> Self

Converts to this type from the input type.
Source§

impl From<&JSTypedArray> for JSObject

Source§

fn from(array: &JSTypedArray) -> Self

Converts to this type from the input type.
Source§

impl From<JSObject> for JSValue

Source§

fn from(object: JSObject) -> Self

Converts to this type from the input type.
Source§

impl From<JSTypedArray> for JSObject

Source§

fn from(array: JSTypedArray) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.