JS Namespaces

by Scott Currell

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>

JavaScript

/** Shorter version of:
 * if (typeof MYAPPLICATION === "undefined") {
 *     var MYAPPLICATION = {};
 * } 
 */
var MYAPPLICATION = MYAPPLICATION || {
    calculateVat: function(base) {
        return base * 1.21;
    },
    product: function(price) {
        this.price = price;
        this.discountPrice = function(discount) {
                          return this.price - this.price * discount;
                       };
    },
    doCalculations: function() {
        var p = new MYAPPLICATION.product(100);
        alert(this.calculateVat(p.getPrice()));
    }
};

var b = new MYAPPLICATION.calculateVat(100);
// don't know why this is logging the object in
// the console rather than calculating base * 1.21
// need to research further
console.log(b);

var p = new MYAPPLICATION.product(150);
console.log(p.price);
console.log(p.discountPrice(0.25));