I've have a JS class that has some default properties. I want to be able to pass in an options object to override the defaults plus some additional ones that aren't defaulted. I'm using lodash's extend
method in my constructor to accomplish this.
One of the default properties is an array. If I instantiate the first instance and push a new value into the array, when I instantiate the second object, the default array contains the object I pushed into the first instance.
Take this code for example...
MyClass = (function() {
var defaults = {
myArr: [],
myProp: 'I\'m a default value'
};
function MyClass(options) {
// console.log(defaults)
if(typeof options === 'object') {
return _.extend(this, defaults, options);
}
else {
return _.extend(this, defaults);
}
}
return MyClass;
})();
var myObj = new MyClass({foo: 'bar'})
myObj.myArr.push('baz')
var mySecondObj = new MyClass();
console.log(mySecondObj) // MyClass {myArr: Array[1]}
I expect mySecondObj.myArr
to be an empty array.
How is it that when I push a value into myObj.myArr
, defaults.myArr
somehow gets changed and is used for subsequent instances of the class?