I'm trying to improve overall performance of a javascript application and i'm trying to create a utility class for all independent functions. Is it a good practice to do that?
Also i have read that is ok to use anonymous functions like this:
(function(){
var Utils = {
test: function () { ... },
test1: function () { ... }
...
}
}())
But for some reason i am unable to use Utils.test() inside my other class, i get
ReferenceError: Utils is not defined
and now i am using
var Utils = {
test: function () { ... },
test1: function () { ... },
....
}
will there be any improvements by doing so or should i just stick to classic separated functions
function test() { ... }
function test1() { ... }
....
Thanks for any help
You need different syntax to work with an IIFE, but I believe it is good practise to do so
var Utils = (function(){
return {
test: function () { ... },
test1: function () { ... }
...
}
}())
For a reasonably-sized project usually you'll have a project namespace under which all the project code falls so you don't unnecessarily pollute the global namespace. You can pass in the namespace as an argument to the IIFE and attach the code you create within it to the namespace. Something like this:
;(function(namespace) {
namespace.Utils = {
test: function() {
console.log('test');
},
test1: function() {
console.log('test1');
}
};
}(this.namespace = this.namespace || {}));
namespace.Utils.test(); // test
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