SoFunction
Updated on 2025-04-13

A case study on the difference between exports and seaJs experience

This article describes the difference between exports and experience in seaJs usage. Share it for your reference, as follows:

1. exports is a helper object. When exports provide APIs to the outside world, you need to use return to return the exports object.

2. You can also provide API directly to the outside world

Reference: /seajs/seajs/issues/242

exports Object

exports is an object that provides module interfaces to the outside.

define(function(require, exports) {
 // Provide foo attributes to the outside  = 'bar';
 // Provide doSomething method to the outside world  = function() {};
});

In addition to adding members to the exports object, you can also use return to provide an interface directly to the outside.

define(function(require) {
 // Provide the interface directly through return return {
  foo: 'bar',
  doSomething: function() {}
 };
});

If the return statement is the only code in the module, it can also be simplified to:

define({
 foo: 'bar',
 doSomething: function() {}
});

The above format is particularly suitable for defining JSONP modules.

Special note: The following writing method is wrong!

define(function(require, exports) {
 // Wrong usage!  !  ! exports = {
  foo: 'bar',
  doSomething: function() {}
 };
});

The correct way to write it is to use return or assign a value to:

define(function(require, exports, module) {
 // Correct writing  = {
  foo: 'bar',
  doSomething: function() {}
 };
});

Tip: exports is just a reference to . When reassigning exports to the factory inside, the value of _ will not be changed. Therefore, assignment to exports is invalid and cannot be used to change the module interface.

Object

The interface provided by the current module to the outside.

The exports parameter passed to the factory constructor is a reference to the object. The interface is only provided through the exports parameter, and sometimes it cannot meet all the needs of developers. For example, when the interface of a module is an instance of a certain class, it needs to be implemented through:

define(function(require, exports, module) {
 // exports is a reference to ( === exports); // true
 // Reassign value to  = new SomeClass();
 // exports is no longer equal to ( === exports); // false
});

Note: The assignment of , needs to be executed synchronously and cannot be placed in the callback function.. The following is not possible:

// (function(require, exports, module) {
 // Incorrect usage setTimeout(function() {
   = { a: "hello" };
 }, 0);
});

There is a call to the above:

// (function(require, exports, module) {
 var x = require('./x');
 // Cannot get the properties of module x a (); // undefined
});

I hope this article will be helpful to everyone's programming.