What I want to accomplish: Create modules using prototyping in javascript so that a user can instantiate a module multiple times each with different options.
The Problem: when using var my_module3 = new module();
and then trying to set the options with my_module3.init({ option: "value" });
does not change the object each time, it only changes it once.
Testing: When using console.log
we can see that it prints out the two objects with the same options even though they are set differently
Object {first: "Barry", second: "Larry", third: "Sam"}
Object {first: "Barry", second: "Larry", third: "Sam"}
Here is my jsFiddle full code: http://jsfiddle.net/11bLouc8/2/
var module = (function () {
// default options
var options = {
first: "test",
second: "test2",
third: "test3"
};
// take in useroptions and replace default options
var module = function(userOptions) {
if (userOptions != null && userOptions != undefined
&& userOptions != 'undefined') {
for (var opt in options) {
if (userOptions.hasOwnProperty(opt)) {
options[ opt ] = userOptions[ opt ];
}
}
}
};
//prototype
module.prototype = {
init: module,
options: options
};
return module;
})();
// create a new instance
var my_module3 = new module();
my_module3.init({
first: "Mike",
second: "Lisa",
third: "Mary"
});
// another instance
var my_module2 = new module();
my_module2.init({
first: "Barry",
second: "Larry",
third: "Sam"
});