0

I want to create multiple instances of an object in Javascript. I know that using Object.create(obj) or using new ObjConstructor(); or using ObjFactory(); (thanks to @WiktorZychla) will let me create different instances.

I understand the differences from this question, and both of them do work when the Object Constructor is coded in a certain way.

However when I use return in my object constructor factory to implement private variables using closure, the two instances created seem to be the same.

This is my object constructor function:

var obj3 = function () {

    variable3 = "Hello World";
    function3_private = function () {

        return variable3;
    };

    return {

        function3_get : function () {

            return variable3;
        },

        function3_set : function (v) {

            variable3 = v;
        },

        function3_print : function () {

            return function3_private();
        }
    };

};  

How do I use this constructor to create two different instances? Or should I make changes in the constructor to achieve the same?

Please suggest best practices if my code is not following any. Here's the fiddle: http://jsfiddle.net/GcD9n/

Community
  • 1
  • 1
srrvnn
  • 609
  • 1
  • 11
  • 20

1 Answers1

1

Your private variables are actually global, because you've missed out the keyword var. This means that any objects you make are all using and modifying the same instance of variable3 and function3_private, and calling

function3_private();

works and prints out the value of variable3.

Timespace
  • 508
  • 4
  • 18
  • Thanks. Adding the var keyword stopped function3_set() from working. The output isn't as I would want. Can you try working with the fiddle? – srrvnn May 24 '14 at 20:40
  • @srrvnn I added var in front of both `variable3` and `function3_private` in the fiddle and it works fine for me. What is `function3_set` now doing for you? – Timespace May 24 '14 at 20:46
  • It works! I didn't add the var for function3_private(), the previous time. – srrvnn May 24 '14 at 20:48