0

I am learning how JS prototype works. I notice that the created object myFoo doesn't inherit a method from Bar if I assign the prototype after creating the object. Is there any way that we can make previous created objects to inherit prototype methods? Thanks

function Foo() {}
function Bar() {}
Bar.prototype.helloBar = function() {
    console.log('hello bar!');
}
var myFoo = new Foo();
Foo.prototype = new Bar(); 
myFoo.helloBar();
Donut
  • 63
  • 1
  • 7
  • 2
    You need to put `Foo.prototype = new Bar();` before create `var myFoo = new Foo();` – Simone Rossaini Feb 08 '22 at 07:38
  • Yep. I mentioned it in the post "I notice that the created object myFoo doesn't inherit a method from Bar if I assign the prototype after creating the object." Is there any way we can assign the prototype later and the previous created Foo objects can still inherit Bar methods. – Donut Feb 08 '22 at 07:40
  • 1
    Not if you just pave over the previous prototype. Works if you *change* it rather than *overwrite* it, though. With that said, this is a very strange case - having objects already create it and having to *completely overwrite what they are*. Sounds like either potential source of weird bugs or [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – VLAZ Feb 08 '22 at 07:50

0 Answers0