0

I'm trying to use module pattern with the following code:

(function(elements) {

    elements.Textbox = function() {
        this.properties = elements.defaultProperties.textboxProperties;
    }

    elements.Textbox.prototype = {
        setSize: function(size) {
            this.properties.size = size;
        },

        getProperties: function() {
            return this.properties;
        },
        getSize: function() {
            return this.properties.size;
        }
    }
}(app.elements || {}));

And trying to create and modify objects like so

var textbox1 = new app.elements.Textbox();
var textbox2 = new app.elements.Textbox();
textbox2.setSize({
    width: 300,
    height: 100
});

But this causes both textboxes to endup with same height and width. I'm new to using Module pattern with Constructor. If I take out Textbox, and then do

var textbox1 = new Textbox();
var textbox2 = new Textbox();
textbox2.setSize({
    width: 300,
    height: 100
});

This works fine. I'm somewhat misunderstood about this, so thanks in advance for help and clarification.

Edit: I've looked at many SO questions, including: Javascript: Module Pattern vs Constructor/Prototype pattern? and they've all been very helpful.

Community
  • 1
  • 1
user
  • 183
  • 1
  • 2
  • 9
  • 7
    This is because all `texbox.properties` refer to the same object `elements.defaultProperties.textboxProperties`. You have to clone it before assigning e.g. `this.properties = Object.assign({}, defaults...)` – georg Jul 28 '16 at 20:46
  • Yup, works. Thanks. Would you have any other comments on that much piece of code, code-cleanliness, maybe it can be better written, etc.? Thank you! – user Jul 28 '16 at 20:52
  • 1
    `|| {}` should probably be either dropped or changed into `|| (app.elements = {})` – Bergi Jul 28 '16 at 20:54
  • Please see the link for the waring for deep-copy. I ended up using JSON.stringify/parse, which works for my case, though it has problems with Date getting converted to String, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign And thanks Bergi. – user Jul 28 '16 at 21:48

0 Answers0