C# namespace mechanism in Javascript

332 Views Asked by At

I'm new to javascript in a way of doing more with the language than fetching data via AJAX on a button click using jQuery.

Coming from a C# background I do not see a direct approach of using namespaces in Javascript. I tried to mimic it using the following code. My question is concerned to the using(namespace); method which copies all from the namespace object to the window object. I have not encountered such coding while searching how to deal with javascript in a modular fashion and I would like to know the folliwing: 1) Does this pattern have a name? 2) What are the pros and cons to the using(namespace);?

console.clear();

var System = {
  IO: {
OutletOption: {
  Console: 1,
  MessageBox: 2
},
Outlet: function Outlet(outletOption) {

  var _self = this;
  var _outletOption = outletOption;

  //private
  _self.log = function(txt) {
    console.log(txt);
  };
  _self.messageBox = function(txt) {
    alert(txt);
  };

  //public
  _self.out = function(txt) {
    switch (_outletOption) {
      case System.IO.OutletOption.MessageBox:
        _self.messageBox(txt);
        break;
      case System.IO.OutletOption.Console:
        _self.log(txt);
        break;
    }
  };

  return {
    out: _self.out
  };
}
  }
};

function using(namespace, scope) {
  console.log(scope);
  for (var key in namespace) {
scope[key] = namespace[key];
  }
}

(function() {
  function execute() {
  
//All your code goes here
using(System.IO, this);
var o = new this.Outlet(this.OutletOption.Console);
o.out("Some test text.");

  };
  return {
execute: execute
  };
})().execute();

1

There are 1 best solutions below

2
On

JavaScript does not have namespaces. If you come from C# you would find easier using TypeScript and maybe Angular2+. TypeScript is JavaScript with types.