1

I understand that Python has what it calls "namespaces", but I'm looking to write some code along the lines of security.crypto.hash.md5("b") and such. JavaScript doesn't have namespaces, but their behavior can be replicated using object notation:

var stdlib = {
    math: {
        constants: {
            e: 2.718281828,
            pi: 3.141596535,
            silver: 2.414213562
        },
        operations: {
            add: function(a, b) {
                return a + b;
            },
            subtract: function(a, b) {
                return a - b;
            },
            multiply: function(a, b) {
                return a * b;
            },
            divide: function(a, b) {
                return a / b;
            }
        },
        abs: function(a) {
            if (a < 0) {
                return 0 - a;
            } else {
                return a;
            }
        },
        sgn: function(a) {
            if (a > 0) {
                return 1;
            } else if (a < 0) {
                return -1;
            } else {
                return 0;
            }
        }
    }
}

This allows for writing code like:

var i = 0;
var j = 1;
var n = stdlib.math.operations.add(i, j);
var constants = Object.create(stdlib.math.constants);
var ops = Object.create(stdlib.math.operations);
var z = ops.multiply(n, constants.e);

In Python, modules are separated into namespaces by placing them in folders, so os and os.path represent $ROOT/osand ``$ROOT/os/path, respectively. Is there a way to avoid that and do something that emulates namespaces like the above trick with JavaScript?

Melab
  • 2,594
  • 7
  • 30
  • 51

1 Answers1

1

If all you're after is the dot notation, you can always create classes? See Is it a good idea to using class as a namespace in Python.

Community
  • 1
  • 1
ChristopherC
  • 1,635
  • 16
  • 31