+ 1

The use of "with" function

I have a js code to deserialize a JS fn from a serialized Function the reason is that I want to transfer it to my web worker it's compatible with web and node so that's good but I found out that it's not recommended to use what do it do is there any alternative? function deserializeFn(serializedObj) { let fn = new Function('with(this) { return ' + serializedObj.value + '; }'); return fn.call(serializedObj.scope); }

8th Jan 2025, 5:51 AM
Creative Creations 1
Creative Creations 1 - avatar
3 Answers
+ 2
Creative Creations 1 A better approach would be not to use "with" ``` const serializedObj = { value: 'return x + y;' }; function deserializeFn(serializedObj) { const { value } = serializedObj; const fn = new Function('x', 'y', value); return fn; } const deserializedFn = deserializeFn(serializedObj); const result = deserializedFn(5, 3); // result will be 8 document.write(result); ```
8th Jan 2025, 6:05 AM
BroFar
BroFar - avatar
0
Godwin Emmydonj please do not spam threads .. follow the forum guidelines https://www.sololearn.com/discuss/1316935/?ref=app https://www.sololearn.com/discuss/3021159/?ref=app
10th Jan 2025, 4:36 AM
BroFar
BroFar - avatar