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
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
Share Improve this question asked Feb 21, 2016 at 15:07 GabrielGabriel 6901 gold badge8 silver badges26 bronze badges 3 |4 Answers
Reset to default 10You 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
Today with ES6 you would probably export all methods in the root of a module and then do import * as Utils from 'utils.js'
Gualtiero Testa wrote about this on his blog. I think that this approch is better if you're on a ES6 env.
The usual approach I adopt (and suggest) is to create an utility class like the following one:
function Util () {}
Util.read = function (sel) {
return jQuery(sel).val();
};
Util.write = function (sel, val) {
jQuery(sel).val(val);
};
How to use the utility functions ?
// read the value of the element with id myinput
var val = Util.read('#myinput');
Utils =
dowindow.Utils =
(browser only) ... – Jaromanda X Commented Feb 21, 2016 at 15:11