Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript object creation best practice
    primarykey
    data
    text
    <p>I have the following javascript :</p> <pre><code> 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); }); </code></pre> <ol> <li><p>Is my approach to object construction a good practice?</p></li> <li><p>I am getting <code>undefined</code> in the helperFunc when trying to access <code>this.prop3</code>.</p></li> <li><p>I have also tried to assign <code>this.prop1 + this.prop2</code> to a local variable and use a function to return this value like so:</p> <pre><code> 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; ... </code></pre></li> </ol> <p>...and when calling this in the helperFunc like this:</p> <pre><code> return this.getTotal(); </code></pre> <p>.. i get <code>this.getTotal</code> is not a function</p> <p>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.</p> <p>TBH - I don't really understand the construct:</p> <pre><code> var myObject = (function() { ... } (); </code></pre> <p>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?</p> <p>Any knowledge imparted would be much appreciated.</p> <p>Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload