locked
using a function to define javascript objects RRS feed

  • Question

  • Hello, like to ask if the  external parenthises are really necessary?   Like here:

    incident.Controller = (...)     //see code block at the end of this question

     I dont think so.   (at least the code works the same for me).

    Also, I would also like to know the difference between the two snippet of code below.

    The benefit writing the code below in a function (the first snippet below) is to scope things to myCompany.incident by using the "use strict" statement.  Like below. Right?  (i would otherwise write it out as in the snippet beneath it)

    myCompany.incident = (function(incident) {
      "use strict";
      incident.Contracts = {
        onLoad: function() {
          var controller =
                  new myCompany.incident.Controller(Xrm);
          controller.load();
        }
      };

      return incident;
    }(myCompany.incident || {}));

    I would otherwise (if not for "use strict";) write it out like this:

       myCompany.incident = myCompany.incident || {};

       myCompany.incident.Contracts = { onLoad: function() {
             var controller = new myCompany.incident.Controller(Xrm);
             controller.load();
           }
         };

    I dont think "use strict;" is the only difference/consquence of the two snippet, which is the reason for this question.

    Thanks, p.

     

    /// <reference path="controller.js"/>
    /*global myCompany: true*/
    myCompany = window.myCompany || {};
    myCompany.incident = (function(incident) {
      "use strict";
      incident.Contracts = {
        onLoad: function() {
          var controller =
                  new myCompany.incident.Controller(Xrm);
          controller.load();
        }
      };
      return incident;
    }(myCompany.incident || {}));
    
    
    
    
     


    Thanks, Paul


    Wednesday, April 8, 2015 6:36 PM

All replies

  • Wrapping a function definition in paras is typically used when invoking the function straight way. Lookup IIFE (https://en.wikipedia.org/wiki/Immediately-invoked_function_expression).

    var fn= function(arg1) { return "result="+arg1;}

    fn points to the unnamed (anonymous) function. So, fn('test') = "result=test".

    equally.

    var fn2= (function(arg1) { return "result="+arg1;})('another test');

    fn2 = "result=another test"

    Advice varies on whether (fn(){})() or (fn(){}()) is best.

    There are cases when using paras is not strictly necessary but aids readability - justification in itself.


    • Proposed as answer by TGJ Gilmore Saturday, January 16, 2016 11:36 AM
    • Edited by TGJ Gilmore Saturday, January 16, 2016 11:37 AM
    Saturday, January 16, 2016 11:36 AM