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

5
  • 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. Commented Oct 3, 2022 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. Commented Oct 3, 2022 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. Commented Oct 3, 2022 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... Commented Oct 3, 2022 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) Commented Oct 12, 2022 at 22:39

2 Answers 2

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

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

Comments

-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.

1 Comment

When instantiating, no copy is made of anything. Neither shallow nor deep.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.