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
}
2
  • 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. Commented Mar 7, 2014 at 6:29
  • I believe you are correct, Commented Mar 7, 2014 at 6:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, so obj is like a type store?
Yes, have a look at how the real MyLibrary is put together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.