I began to learn more about how to use JavaScript objects, and I tried to write an object in JavaScript that allows me to set some constructor arguments during initialization.
I have to say that there are several different “ design patterns ” in JavaScript that are probably mixed with syntax and much more. Through my research, I have found various StackOverflow articles, such as:
What I would like to do with my object, set some internal / private variables at the initialization point, as shown below:
<script> var TestObj = new Dispatch( 100 ); console.log( TestObj.getConstructorValue() ); </script>
Although at the present time the method of creating the object currently Test returns undefined when trying to access it after its initialization:
<script> $(document).on('ready', function(){ var TestObj = new Dispatch( 100 ); //Set post-initialised variables & set to '5' TestObj.setOrderNumber( 5 ); //Retrieves 5 console.log( "Accessing Property: " + TestObj.OrderNumber ); //Method for getting orderNumber Property, Returns 5 console.log( "Method for Order Number: " + TestObj.getOrderNumber() ); //Method for getting would-be constructor value console.log( TestObj.getTest() ); //Returns Undefined console.log( TestObj.Test ); //Returns Undefined }); </script>
Javascript
<script> var Dispatch = function( Arg1 ) { var OrderNumber; var Test; var setOrderNumber = function( orderNum ) { this.OrderNumber = orderNum; }; this.constructor = function( str ) { this.Test = str; }; this.constructor( Arg1 ); return { getOrderNumber : function(){ return this.OrderNumber; }, setOrderNumber : setOrderNumber, getTest : function() { return this.Test; } }; }; </script>
What I tried (1)
I tried installing it directly:
<script> var Dispatch = function( s ) { var Test = s; return { getTest : function() { return this.Test; } } }; TestObj.getTest(); </script>
What I tried (2)
I also tried to access the variable by slightly mixing the return function:
<script> var Dispatch = function( s ) { var Test; var getTestVar = function() { return this.Test; } this.constructor = function( str ) { this.Test = str; }; this.constructor( s ); return { getTest : getTestVar }; }; TestObj.getTest(); </script>
I played with other methods, although it would be nice to get a written understanding of why I did the wrong thing to get my constructor to work.
Here's a jsFiddle that shows it all in action. I apologize for the rather long post and my ignorance of the JavaScript object!