简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM