0

If I have a JavaScript constructor function:

function Foo() {}
Foo.prototype.bar = 123

Now I create a new object from Foo and change the bar property on prototype object.

const foo = new Foo()
Foo.prototype.bar = 321
console.log(foo.bar) // 321

But If I replace Foo.prototype with a object like this:

const foo = new Foo()
Foo.prototype = { bar: 321 }
console.log(foo.bar) // 123

Why the two code snippets' output is different?

ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • 1
    Because instances already created reference the old *constructor.prototype* object via their internal `[[Prototype]]` property. That value is assigned when the instance is created. To change that, use [*Object.setPrototypeOf*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) but read the warnings (it's not a good thing to do). – RobG Dec 23 '21 at 08:56
  • 1
    `foo` points to the *prototype object*, not to `Foo.prototype`. If you replace `Foo.prototype`, `foo` will still point at the old *object*. Same as `let a = {}; let b = a; a = {}`. – deceze Dec 23 '21 at 08:57

0 Answers0