I understand how things like proper name-spacing and the Module Pattern help issues associated with leaking into the global-scope.
I also completely see the value of resource dependency-management provided for in the require() protocol outlined in the CommonJS Specification.
However, I am befuddled as to the benefit of the AMD define() function’s use and purpose.
The CommonJS signature for define is:
define(id?, dependencies?, factory);
Additionally…
- I see people wrapping their Module
Pattern plug-ins withdefine()when
BOTH create an object at the
global-scope. - A file containing a normal Module
Pattern plug-in can be loaded
asynchronously as well.
At first, it “seemed” like yet-another plug-in wrapper…until I began to see folks use it alongside the Module Pattern.
So My Questions Are:
- What does the
define()protocol
outlined in CommonJS specification
buy me? - Is it somehow more eloquent?
- Is it meant to replace the Modular Pattern?
- Is it somehow faster?
- If so, why?
Define is a great way to pass modular objects back without relying on global scope.
The particular API of define varies from library to library though.
Here the basic idea is that you call define in a file to define what that module is. Then when you require the file you get the module. This cuts out the middle man that is global scope.
It’s no faster though (It’s slower then injecting into global scope).
Using
requireanddefineyou only have two global values.The particular
defineexample above matches the requireJS API