4

I've started to try learn how to use JavaScript Objects more extensively and I've been attempting to write an Object in JavaScript that allows me to set some Constructor arguments on initialisation.

I've got to say, there's quite a few different 'design patterns' in JavaScript that I've probably got myself a little mixed up with syntax and whatnot. Through my research I've found various StackOverflow articles such as:

  1. JavaScript constructors using JavaScript object literal notation
  2. Constructors in JavaScript objects

What I'd like to do with my object set some internal/private variables at the point of initialisation like below:

<script>
   var TestObj = new Dispatch( 100 );
   console.log( TestObj.getConstructorValue() );
   //Would Return 100.
</script>

Although Currently, The way the object is built up is currently Test returning undefined when attempting to access it after it being initialised:

<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 {

            /**
             *  Getter for OrderNumber
                **/
            getOrderNumber : function(){
                return this.OrderNumber;
            },

            /**
             *  Setter for OrderNumber
            **/
            setOrderNumber : setOrderNumber,

            /**
             *  Getter for Test
            **/
            getTest : function() {
                return this.Test;   
            }
        };

    };  
</script>

What I've Tried (1)

I've attempted to set it directly:

<script>
var Dispatch = function( s ) {

    /**
     * Assign constructor
     * to Test
    **/
    var Test = s;

    return {
       getTest : function() {
           return this.Test;    
       }
    }
};

TestObj.getTest(); //Returns undefined
</script>

What I've Tried (2)

I've also attempted accessing the variable by mixing up the function return slightly:

<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(); //Returns undefined
</script>

I've toyed around with other methods, although, It would be nice to get an written understanding to why I've gone wrong to making my constructor work.

Here's a jsFiddle that shows all this in action. Apologies for quite a long post & my JavaScript Object ignorance!

Community
  • 1
  • 1
MackieeE
  • 11,751
  • 4
  • 39
  • 56
  • variable declared with var are constructor's variables, you cannot acces them with this, beacuse this points to object constructed with calling constructor with new. you can acces them through closure. another thing - if you return explicitly defined object, there is no link with constructor's prototype – magyar1984 Sep 24 '13 at 10:38

3 Answers3

2

You have really confused many concepts.
This is what you are looking for:

var Dispatch = function( s ) {
   /**
    * Assign constructor
    * to Test
   **/
   this.Test = s;
   this.getTest = function() {
      return this.Test;    
   }
};

Thus:

TestObj = new Dispatch(7);

Will result in the object:

Dispatch {Test: 7, getTest: function}

and:

TestObj.getTest();

Will return 7.

You can look here for more proper info about constructors:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

bldoron
  • 1,050
  • 4
  • 20
  • 37
  • Much thanks for clarifying that for me =) And yes, after reading a few articles on JavaScript function/object construction, I won't lie - it's diverse. – MackieeE Sep 24 '13 at 12:00
2

You can use this pattern

function myObject (param1) {
    var myPrivateMemberValue1 = param1;

    return {
        getPrivateMemberValue1: function() {
            return myPrivateMemberValue1;
        }
    };
}
console.log(new myObject("thefourtheye"));
console.log(new myObject("thefourtheye").getPrivateMemberValue1());

Output

{ getPrivateMemberValue1: [Function] }
thefourtheye

Explanation:

We use closure here. When the parameter is passed to the constructor, it is stored in the local variable. Then we return an object with getPrivateMemberValue1 function, which still has access to the variable, which is local to the function, because of closure. So you can make variables private like this.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Just wanted to say thank you for providing an nice answer & explanation, it seems my original code was a mixture of this & one bbldoron provided. Although his was a little sooner and the pattern I would perfer to stay with going forward, thank you again though =) – MackieeE Sep 24 '13 at 11:35
1
    function Dispatch(s) {
        var test = s;
        this.returnTest = function () {
            return test;
        }
    }

    var no = new Dispatch(5);
    no.returnTest(); // 5

There is no way to access test variable directly, because it's not member of the newly created object, but you could access it in closure.

magyar1984
  • 186
  • 4