[Solved] closure in webworker-theads [closed]


1. Alternative to Object Oriented programming

In theory, anywhere you can use a class/constructor you can use a closure instead. They both essentially perform the same thing: encapsulate data and maintain state – but via different mechanisms. Objects maintain state using context (Java calls it “scope” but because Java does not actually have real scopes) and closures do it using scope.

Closures are especially useful for replacing single-method classes (which surprisingly there are many uses of):

Let’s take a simple file logger. An OO implementation could be:

class Logger {
    constructor (filename) {
        this.logfile = fs.openSync(filename,'a');
        this.log.bind(this);
    }

    log (txt) {
        const now = new Date().toISOString();
        fs.write(this.logfile, `${now} : ${txt}\n`);
    }
}

// usage:
const logger = new Logger('file.log');
logger.log('Hello');

The same logic can be implemented using a closure instead:

function makeLogger (filename) {
    const logfile = fs.openSync(filename,'a');

    return function (txt) {
        const now = new Date().toISOString();
        fs.write(logfile, `${now} : ${txt}\n`); // <-- using closure here!
    }
}

// usage:
const log = makeLogger('file.log');
log('Hello');

Depending on who you talk to, the closure implementation is easier to read (I’m one of the people who feel more comfortable with closures than classes). It is not only shorter but the state is also contained and cannot be changed from other code.

2. Generally anywhere you need a new scope (need to hide something)

Since functions are the ONLY mechanism for manipulating scope you will also need to use closures to create scope. This is especially useful in security critical code such as code dealing with authentication and financial transactions that need to interact with 3rd-party libraries.

2.1. Node modules

Node.js specifically uses closure to implement something that does not exist in javascript: file scope.

Modules in node are loaded inside an IIFE thereby creating a closure. All variables in a module file are visible to all functions defined in the file (closure) but not visible to other modules (unless declared without a var, let or const). Ryan Dahl did not want to modify Javascript as a language but just add a framework on top of the language to make it useful outside browsers. Fortunately Javascript is powerful enough (has closures) that this is possible.

Real-world examples

There are several real-world examples of large-scale uses of closures:

  • React.FunctionComponent is a recent feature in React.js that allows users to use a closure to implement React components instead of a class. This often cuts down on lines of code and complexity (yes, this is more front-end related but it is very large scale)

  • async.js uses closures a lot to keep track of asynchronous operations

  • Express.js is mixed. While most of the code is OO it also uses closures especially in the middleware/routing architecture.

5

solved closure in webworker-theads [closed]