I have a variable api in which I have more methods that I want to use in test variable and both are in global context.
I think it would be better if I put them on window.document and I wonder what other options could be.
var api = (function(){
this.run= function(){
console.log("run api");
};
return this;
})();
// test is in separate file
var test = (function(one_){
this.as = function(){
console.log(one_.run());
};
return this;
})(one);
test.as();
var company = company || {} ;
company.doSomething = function() {
};
company.test = {};
company.test.submodule = {};
company.test.submodule.doSomething = function() {};
company.api = {};
company.api.submodule = {};
You should generally avoid defining variables globally. For clear maintainable code, use objects as namespaces and avoid polluting the global namespace.
This also greatly enhances default JS functionality. If you are really keen on it, add something like require.js
to your projects and you will get a very nice Java-like functionality.
So with require.js
, your company.api
and company.test
can be placed in different files and require
each other, just like you would do an import company.test
with a Java package
.
Namespacing is a very efficient practice. You get:
window
vs global
object bugs.Important
It it also fairly dangerous to use this
in static contexts. JavaScript naming conventions dictate that static will be named starting with lower-case char and classes will be defined starting with an uppercase char, use camelCase of course.
Again, a very powerful and useful convention. It tells a developer that something is static or a class in the blink of an eye. So for instance, if you have:
company.test.submodule.doSomething = function() {
// this is a static function. It's a normal property, it's not nested under the prototype.
};
Instead if you want to make a class, you can use the this
reference in the correct way.
// Notice Person starts with uppercase P.
company.test.subModule.Person = function(name) {
this.name = name;
this.numberOfEyes = 2;
};
company.test.subModule.Person.prototype.cryMeARiver = function() {
console.log(this.name + " can cry a river.");
};
Now inside whatever other function, you can do:
company.api.someSubModule.peopleCryRivers = function() {
// this is again a static context.
var bodgan = new company.test.subModule.Person("Bogdan");
var andreea = new company.test.subModule.Person("Andreea");
bodgan.cryMeARiver();// will output "Bogdan can cry a river."
andreea.cryMeARiver();// will output "Andreea can cry a river."
// etc..
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With