Skip to content

Instantly share code, notes, and snippets.

@TakahikoKawasaki
Last active August 29, 2015 14:18
Show Gist options
  • Save TakahikoKawasaki/97f23cdd26b5b1a681d1 to your computer and use it in GitHub Desktop.
Save TakahikoKawasaki/97f23cdd26b5b1a681d1 to your computer and use it in GitHub Desktop.
Function to define a namespace in JavaScript.
/*
* Copyright (C) 2015 Neo Visionaries Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Source Code Location:
*
* namespace.js
* https://gist.github.com/TakahikoKawasaki/97f23cdd26b5b1a681d1
*/
/**
* Define a namespace.
*
* If 'aaa.bbb.ccc' is given, aaa.bbb.ccc is created if it does not exist yet.
* The hash object that represents the last layer is returned. For example,
* if 'aaa.bbb.ccc' is given, the hash object that represents ccc is returned.
*
* Usage:
*
* // Define a namespace 'aaa.bbb.ccc' and add a function 'hello'
* // under the namespace which prints 'Hello, world.'.
* namespace('aaa.bbb.ccc').hello = function() {
* print('Hello, world.');
* };
*
* // Execute the function.
* aaa.bbb.ccc.hello();
*/
namespace = function(packageName)
{
// Local variables.
var layers, layer, currentLayer, i;
// Split the given string into an array.
// Each element represents a namespace layer.
layers = packageName.split('.');
// If the top layer does not exist in the global namespace.
if (eval("typeof " + layers[0]) === 'undefined')
{
// Define the top layer in the global namesapce.
eval(layers[0] + " = {};");
}
// Assign the top layer to 'currentLayer'.
eval("currentLayer = " + layers[0] + ";");
for (i = 1; i < layers.length; ++i)
{
// A layer name.
layer = layers[i];
// If the layer does not exist under the current layer.
if (!(layer in currentLayer))
{
// Add the layer under the current layer.
currentLayer[layer] = {};
}
// Down to the next layer.
currentLayer = currentLayer[layer];
}
// Return the hash object that represents the last layer.
return currentLayer;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment