2

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

Dai
  • 141,631
  • 28
  • 261
  • 374
HamzaElkotb
  • 138
  • 1
  • 7
  • 4
    `this.options` refers `options` object in the prototype, that's a common object for all the instances of `Person`. 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. – Teemu Oct 03 '22 at 11:39
  • 1
    Hint: run this at the end of your script: `console.log( "Object.is: %o", Object.is( foo.options, bar.options ) );` - it will print `"Object.is: true`. – Dai Oct 03 '22 at 11:40
  • `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. – VLAZ Oct 03 '22 at 11:41
  • 1
    @VLAZ I think the OP expects the prototype object to be copied (a-la `Object.assign`) when the `Person` constructor runs. I'll admit that I've forgotten how to use `prototype` such that instances _don't_ share state... – Dai Oct 03 '22 at 11:42
  • @Dai You *don't* use the prototype for stateful things. (You *could* potentially do `this.options = Object.create(this.options)` in the constructor, to have nested inheriting objects, but I wouldn't recommend it) – Bergi Oct 12 '22 at 22:39

2 Answers2

0

thanks to all people who answered this question.

1- both foo and bar are pointing to the same object, that called options.

2- they are pointing to the same passed value called name.

3- both foo and bar are objects, so they are references.

4- and they are containing object called options and which also reference.

5- so when we change name value in options object in any one of foo it will be changed to options object name value in all created objects funding Person function.

I think this is the answere

HamzaElkotb
  • 138
  • 1
  • 7
-2

Because when you've instantiated foo and bar they made a shallow copy of Person.prototype.options object.

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

// are foo.options and bar.options pointing to the same options object?
console.log(foo.options===bar.options)

As you can see foo.options===bar.options returns true.

Logan Lee
  • 807
  • 9
  • 21