Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript module exports pattern

can someone please explain what's the exports variable for:

copied from backbone.js, I also noticed spine.js uses the same pattern.

https://gist.github.com/1375748

var Backbone;
if (typeof exports !== 'undefined') {
    Backbone = exports;
} else {
    Backbone = root.Backbone = {};
}
like image 337
Xiaotian Guo Avatar asked Nov 18 '11 06:11

Xiaotian Guo


People also ask

What does module exports do in JavaScript?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

What is JavaScript module pattern?

Module pattern. The Module pattern is used to mimic the concept of classes (since JavaScript doesn't natively support classes) so that we can store both public and private methods and variables inside a single object — similar to how classes are used in other programming languages like Java or Python.

What can you export with module exports?

By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.

How many exports can a module have?

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.


1 Answers

That module pattern is part of the CommonJS specification called CommonJS Modules:

In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.

So basically adding to the exports object defines the API your module exposes.

like image 89
Daff Avatar answered Oct 11 '22 14:10

Daff