While reading "Object-Oriented JavaScript" on Mozilla's website, I stumbled upon this note:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
However, the note is not clear about what is meant by "language-level difference".
Does it mean there are two ways of writing the same thing? Or that there are two terms that refer to the same thing?
An object namespace protects named objects from unauthorized access. Creating a private namespace enables applications and services to build a more secure environment. A process can create a private namespace using the CreatePrivateNamespace function.
JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.
You have already learned that JavaScript variables are containers for data values. Objects are variables too. But objects can contain many values. The values are written as name:value pairs (name and value separated by a colon).
Names are what can be traditionally thought of as "variables". Namespaces are the places where names live.
You've taken the quote out of context. The answer is in the paragraph above the quote:
A namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties, and objects.
(Emphasis mine)
The quote:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
Is just saying that this means a "namespace" is just a object used as a "namespace".
There are no "real" namespaces in JS.
Some languages have an actual namespace which is not the same thing as an object. JavaScript is not one of those languages, so objects are used for this purpose.
For example, the Math
functions like Math.round
and Math.abs
, are all namespaced in the Math
object. They aren't really contextual methods like toString
is (at least not in any implementation I've found), just collected under an object to keep it organized. *
* They are technically methods, because they are accessible by a property on an object (a definition that technically makes all global functions methods because they are available through the global object (ie. window.Function()
)), but unlike methods like toString
, or the methods of most console
implementations like console.log
they do not depend on the object they are called on and the this
value is irrelevant. The Math
object is used purely for namespacing, not because of the context it gives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With