0

I am trying to put default object values in a prototype of an function. But that is causing prototype "defaults" object to be changed by another instance. Why is that happening? I know I can put defaults object inside function, but that is not what I would like to do. Can someone explain me why prototype variable is overridden by second instance? Demo is here: https://jsfiddle.net/c0zg5vjp/2/

window.foo = function(options) {

    this.settings = jQuery.extend({}, this.defaults, options || {});

    this.bar = function() {

        this.settings.classes.push('new_class');
    }
}

window.foo.prototype.defaults = { 'classes' : ['default'] };

var instance = new foo();

instance.bar();

var instance_2 = new foo();

instance_2.bar();

alert( instance_2.settings.classes.join() );
0

1 Answer 1

2

jQuery.extend({}, this.defaults

is setting a property named classes on a new object, and setting it to the same memory pointer to the array ['default'] as the original.

In other words, both instances have separate "settings" objects that both have a classes property that point to the same array.

You should use the "deep" version of extend: https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN

jQuery.extend(true, {}, this.defaults, ...

which would recurse into your array and clone that too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.