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?
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.