Share JavaScript Code between Browser (front-end) and Node (back-end)
One of the benefits coding in JavaScript is the ability to share code between
browser (front-end) and Node (back-end) environments.
To share code between two different environment, first need to understand what
are specific to browser and what are specific to Node. Shared code should be
agnostic to both environments.
In browser environment, there is an obvious one: window
object. In Node
environment, there are a few objects that are not globally defined in browser:global
, process
, module
, exports
and more, see global objects. All
these variables work, but exports
is preferred.
|
|
Once environment is identified, then it is just the matter of writing style,
either browser style or Node style.
For example, writing in Node style by passing the exports
as the parameter:
|
|
By using browser style, here is an example from the annotated source code of
Underscore:
|
|
To make it easier without concerning the backward compatibility:
|
|
this
is the same as window
object in the browser environment.
|
|
One more thing, writing in CoffeeScript is even better, because the compiled
code is already wrapped in closure, fewer indentation is needed.
|
|
Compile to JavaScript by CoffeeScript 1.6.3:
|
|
Everything will be encapsulated inside the foo
object.