Namespaces & ReferenceError: <namespace> is not defined. Why?


#1

I want to define individual modules, which in turn would implement business rules for the app. I wanted to follow simple naming/namespacing solution like BusinessRule.WHO.WHAT. I don’t know if this matters but I’ve put them under server/user/businessRules directory. Here is is my business rule module:

BusinessRule = {};
BusinessRule.User = {};
BusinessRule.User.canUserBeAdded = (function () {
	"use strict";
	var result = {
		isValid: true,
		errors: []
	};
	function run() {

		return result;
	}
	return {
		run: run
	};
}());

and this works but I don’t understand why these changes crash the app.

  1. if I change it to:

    BusinessRule = BusinessRule || {};
    BusinessRule.User = {};

  2. or this:

    //BusinessRule = BusinessRule || {};
    BusinessRule.User = {};

They all crash with “ReferenceError: BusinessRule is not defined” - why? What’s the proper way of doing this?


#2

In JavaScript, if you try to read a variable that isn’t defined, it crashes the app. Before, you were just assigning to BusinessRule; in this new code, you are also reading from it. Try this:

if (typeof BusinessRule === "undefined") {
  BusinessRule = {};
}

typeof is a special operator that doesn’t suffer from this issue.


#3

Works like a charm. Thanks Sash!