Universal singleton/namespace pattern for js (node.js or browser)


// File: first.js
// first declaration of singletonName (e.g. for abstract interfaces)
(function(singletonName) {
 singletonName.publicProperty = 'public property value of first declaration';
 var privateProperty = 'privat property value of first declaration';
 singletonName.publicMethod = function() {
  console.log('publicMethod of first declaration to be owerwritten');
 };
 singletonName.toBeOverridden = function() {
  console.log('publicMethod of first declaration to be overridden ');
 };
 privateMethod = function() {
  console.log('privateMethod of first declaration');
 };
} (global.singletonName = global.singletonName || {}));

// File: second.js
// second declaration of singletonName can extend, override and call inherited finctionality
(function(singletonName) {
 singletonName.publicProperty = 'public property value of second declaration will overwrite publicProperty of first declaration';
 var privateProperty = 'privat property value of second declaration will not overwrite privateProperty of first declaration';
 singletonName.publicMethod = function() {
  console.log('publicMethod of second declaration will overwrite publicMethod of first declaration');
 };
 privateMethod = function() {
  console.log('privateMethod of second declaration will not overwrite privateMethod of first declaration');
 };
 singletonName.toBeOverridden = singletonName.toBeOverridden.override(function() {
  console.log('Overridden method');
  this.inherited(); // call to the inherited variant of this method
 });
 singletonName.wrapper = function() {
  console.log('Wrapper for override previous singleton structure');
  singletonName.publicMethod = singletonName.publicMethod.override(function() {
   console.log('Overridden method');
  });
 };
 // Place singletonName initialization code here
 if (1==1) {
  console.log('singletonName initialization code');
 }
} (global.singletonName = global.singletonName || {}));


// File: global.js
if (typeof(window) != 'undefined') window.global = window;

Function.prototype.override = function(fn) {
 var superFunction = this;
 return function() {
  this.inherited = superFunction;
  return fn.apply(this, arguments);
 }
}

// File: test.js
require('./global.js');
require('./first.js');
require('./second.js');
singletonName.wrapper();

Комментарии

Популярные сообщения из этого блога

Введение мета-уровеня

Метамодель в задачах интеграции информационных систем

CLEAR