Search code examples
javascriptobjectclosurescreation

Javascript object creation best practice


I have the following javascript :

            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();


            $(function() {

                MyObject.init(someArgs);

            });
  1. Is my approach to object construction a good practice?

  2. I am getting undefined in the helperFunc when trying to access this.prop3.

  3. I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

            function Setup(args) {
                    var total;
    
                    this.prop1 = args.x;
                    this.prop2 = args.y
    
                    total = this.prop1 + this.prop2;
                    this.getTotal = function() {
                            return total;
                    };
    
                    this.prop3 = this.prop1 + this.prop2;
                    ...
    

...and when calling this in the helperFunc like this:

                       return this.getTotal();

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

                       var myObject = (function() { ... } ();

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem


Solution

  • To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:

    That is because the value of “this” is different to the value of “this” when the object was created.

    So in your case:

    ...
      var _this = this.prop3;
      function helperFunc() {
        return _this;
      }
    ...
    

    might achieve what's desired.