Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility class for functions

Tags:

javascript

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

like image 480
Gabriel Avatar asked Feb 21 '16 15:02

Gabriel


2 Answers

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 () { ... }
    ...
 }

}())
like image 93
Simon H Avatar answered Oct 09 '22 09:10

Simon H


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
like image 36
Andy Avatar answered Oct 09 '22 10:10

Andy