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. Using namespaces in such a scenario will isolate these contexts such that the same identifier can be used in different namespaces. In this article, we will discuss how namespaces can be initialized and used in JavaScript. JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.
Syntax:
- To initialise an empty namespace
var <namespace> = {};
- To access variables in the namespace
<namespace>.<identifier>
Below example illustrates the namespace in JavaScript:
Example: As shown below, the identifier startEngine
is used to denote different functions in car and bike objects. In this manner, we can use the same identifier in different namespaces by attaching it to different global objects.
<script> var car = { startEngine: function () { console.log( "Car started" ); } } var bike = { startEngine: function () { console.log( "Bike started" ); } } car.startEngine(); bike.startEngine(); </script> |
Output:
Car started Bike started