Reputation: 610
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/
Upvotes: 0
Views: 72
Reputation: 508
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
.
Upvotes: 1