Skip to content

Commit 5627ab2

Browse files
committed
Add PyJsValue::construct()
1 parent 93cdd94 commit 5627ab2

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

wasm/lib/src/js_module.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,36 @@ impl PyJsValue {
162162
.map_err(|err| convert::js_to_py(vm, err))
163163
}
164164

165+
#[pymethod]
166+
fn construct(
167+
&self,
168+
args: Args<PyJsValueRef>,
169+
opts: NewObjectOptions,
170+
vm: &VirtualMachine,
171+
) -> PyResult<PyJsValue> {
172+
let ctor = self
173+
.value
174+
.dyn_ref::<js_sys::Function>()
175+
.ok_or_else(|| vm.new_type_error("JS value is not callable".to_string()))?;
176+
let proto = opts
177+
.prototype
178+
.as_ref()
179+
.and_then(|proto| proto.value.dyn_ref::<js_sys::Function>().clone());
180+
let js_args = Array::new();
181+
for arg in args {
182+
js_args.push(&arg.value);
183+
}
184+
let constructed_result = if let Some(proto) = proto {
185+
Reflect::construct_with_new_target(ctor, &js_args, &proto)
186+
} else {
187+
Reflect::construct(ctor, &js_args)
188+
};
189+
constructed_result
190+
.map(PyJsValue::new)
191+
.map_err(|err| convert::js_to_py(vm, err))
192+
}
193+
194+
165195
#[pymethod(name = "typeof")]
166196
fn type_of(&self, _vm: &VirtualMachine) -> String {
167197
type_of(self.value.clone())

0 commit comments

Comments
 (0)