Why does this code return bar twice, not foo then bar?
function Person(name) {
if (name) this.options.name = name;
}
Person.prototype.options = {
name: "Default name"
};
var foo = new Person("foo");
var bar = new Person("bar");
console.log(foo.options.name);
console.log(bar.options.name);
does it because of the reference and can you guys explain
this.optionsrefersoptionsobject in the prototype, that's a common object for all the instances ofPerson. Make it like this:this.name = name || this.options.name;, that way you can read a default name from options, and give an individual name for every instance if it is passed.console.log( "Object.is: %o", Object.is( foo.options, bar.options ) );- it will print"Object.is: true.options = { name: "Default name" }; foo = options; bar = options; foo.name = "foo"; bar.name = "bar";basically the same as what your code does. Modifying the same object leads to...modifying the same object.Object.assign) when thePersonconstructor runs. I'll admit that I've forgotten how to useprototypesuch that instances don't share state...this.options = Object.create(this.options)in the constructor, to have nested inheriting objects, but I wouldn't recommend it)