简体   繁体   中英

Function prototype object is changed on another instance

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() );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM