0

I have a Shape class, it's defined in the global scope:

function Shape(t) {
   this.type;                            
   Shape.prototype.init = function(){
      this.type = t;
      //more work here             
   }
   this.init();                                         
}  

I want to consolidate all global functions/classes into a single class to avoid conflicts with global namespace

function Util(){}
Util.Shape = function(){...}
Util.Point = function(){...}

That works, but I don't like repeating Util. each time, so I use a property like a namespace for related functions, in this case, math:

Util.math = {
   Shape: function(t) {
      this.type;                            
      Shape.prototype.init = function(){
         this.type = t; 
         //more work here            
      }
      this.init();                                         
   },
   Point: function(t) {...}
}       

But that doesn't work; complains about this.init(); makes sense since Shape.prototype is not needed here, so it's removed:

Util.math = {
   Shape: function(t) {
      this.type;                            
      this.init = function(){
         this.type = t;             
      }
      this.init();                                         
   }
}

Works now:

var square = new Util.math.Shape('square');
var circle = new Util.math.Shape('circle');         
console.log(square.type);  // 'square'
console.log(circle.type);  // 'circle'

Questions:
Any issue with this approach? More effective/cleaner way to do it?

Also, why does this not work? (this is coolness)

Util.math = {
   Shape: function(t) {
      this.type;                            
      this.init = function(){
         this.type = t;             
      }                                         
   }.init(); //<------coolness
}
Community
  • 1
  • 1
raffian
  • 31,267
  • 26
  • 103
  • 174
  • `But that doesn't work; complains about this.init()` because a function expression is different to a function declaration. `makes sense since Shape.prototype is not needed here`—if it's "not needed here" then it was not needed before. – RobG Mar 07 '14 at 06:29
  • I believe you are correct, – raffian Mar 07 '14 at 06:37

1 Answers1

0

You can also do:

var myLib = (function() {

  var obj = {};

  function Shape(t) {
    this.init(t);
  }

  Shape.prototype.init = function(t){
     this.type = t;
  }

  obj.Shape = Shape;

  // more stuff

  return obj;
}());

var shape = new myLib.Shape('circle');

console.log(shape.type); // circle

Assuming that the init thing is just an example.

RobG
  • 142,382
  • 31
  • 172
  • 209