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
}