@@ -134,6 +134,47 @@ impl JSObject {
134
134
}
135
135
}
136
136
137
+ /// Set a property onto an object.
138
+ ///
139
+ /// This can be used to create a new property, or to update an existing property.
140
+ ///
141
+ /// * `name`: A value that can be converted to a [`JSString`] containing
142
+ /// the property's name.
143
+ /// * `value`: A value containig the property's value.
144
+ ///
145
+ /// ```
146
+ /// # use javascriptcore::{JSContext, JSValue};
147
+ /// let ctx = JSContext::default();
148
+ /// let object = JSValue::new_from_json(&ctx, r#"{"a": 10}"#).expect("valid object").as_object().unwrap();
149
+ /// object.set_property("b", JSValue::new_number(&ctx, 11.)).unwrap();
150
+ ///
151
+ /// assert!(object.has_property("a"));
152
+ /// assert!(object.has_property("b"));
153
+ /// ```
154
+ pub fn set_property < S > ( & self , name : S , value : JSValue ) -> Result < ( ) , JSException >
155
+ where
156
+ S : Into < JSString > ,
157
+ {
158
+ let name: JSString = name. into ( ) ;
159
+ let mut exception: sys:: JSValueRef = ptr:: null_mut ( ) ;
160
+ let context = self . value . ctx ;
161
+
162
+ unsafe {
163
+ sys:: JSObjectSetProperty ( context, self . raw , name. raw , value. raw , 0 , & mut exception)
164
+ }
165
+
166
+ if !exception. is_null ( ) {
167
+ return Err ( JSException {
168
+ value : JSValue {
169
+ raw : exception,
170
+ ctx : context,
171
+ } ,
172
+ } ) ;
173
+ }
174
+
175
+ Ok ( ( ) )
176
+ }
177
+
137
178
/// Call this object considering it is a valid function.
138
179
///
139
180
/// ```rust
@@ -287,6 +328,24 @@ mod tests {
287
328
assert_eq ! ( names[ 0 ] , "id" ) ;
288
329
}
289
330
331
+ #[ test]
332
+ fn can_set_property ( ) -> Result < ( ) , JSException > {
333
+ let ctx = JSContext :: default ( ) ;
334
+ let object = JSValue :: new_from_json ( & ctx, r#"{"foo": "bar"}"# )
335
+ . unwrap ( )
336
+ . as_object ( ) ?;
337
+
338
+ assert ! ( object. has_property( "foo" ) ) ;
339
+ assert ! ( !object. has_property( "baz" ) ) ;
340
+
341
+ object. set_property ( "baz" , JSValue :: new_string ( & ctx, "qux" ) ) ?;
342
+
343
+ assert ! ( object. has_property( "baz" ) ) ;
344
+ assert_eq ! ( object. get_property( "baz" ) . as_string( ) ?. to_string( ) , "qux" ) ;
345
+
346
+ Ok ( ( ) )
347
+ }
348
+
290
349
#[ test]
291
350
fn can_use_as_jsvalue_via_deref ( ) {
292
351
let ctx = JSContext :: default ( ) ;
@@ -297,7 +356,7 @@ mod tests {
297
356
}
298
357
299
358
#[ test]
300
- fn call_as_function ( ) -> Result < ( ) , JSException > {
359
+ fn can_call_as_function ( ) -> Result < ( ) , JSException > {
301
360
let ctx = JSContext :: default ( ) ;
302
361
let global = ctx. global_object ( ) ?;
303
362
let math = global. get_property ( "Math" ) . as_object ( ) ?;
0 commit comments