Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeze objects using web-worker

I have an array of collections which needs to be freezed using web-worker. Sample below shows single collection freezing.

var worker = new Worker("worker.js");
worker.onmessage = function (e) { // WATCH MESSAGES FROM THE WORKER
    var data = e.data;

    // TEST: freezed collection property changes here in main scope. Weird!!!
};

worker.postMessage(JSON.stringify({
        'collection' : someHugeJSON_object
    }));

// In my worker.js

function deepFreeze(){
    // my freezing logic
}

onmessage = function (e) {

    var data = JSON.parse(e.data);
    freezedJSON_object = deepFreeze(data.collection);   

    // TEST: collection property does not change in worker scope after freezing

    // DONE FREEZING EVERYTHING... PHEW!!!
    postMessage({ 
        'collection' : freezedJSON_object
    });
}

Does enumerability, configurability, or writability properties of an object, restricted to a particular scope?

like image 569
Akshay Gundewar Avatar asked Aug 24 '26 10:08

Akshay Gundewar


1 Answers

When you call postMessage(obj) you don't send obj - it's cloned using structured clone algorithm.

MDN page is rather explicit about what happens to frozen objects:

Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object is marked read-only using a property descriptor, it will be read-write in the duplicate, since that's the default condition.

So you can't freeze object in WebWorker and send it back to main thread.

By the way - you don't have to call JSON.stringify on messages passed to WebWorker.

like image 155
Ginden Avatar answered Aug 27 '26 08:08

Ginden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!