Reputation: 2129
I have an instance of a class, but I don't have access to that instance, only to the class itself. Can I modify the prototype of the class so that the instance receives an update to its methods also?
class B { c() { console.log('B') } }
class C { c() { console.log('C') } }
const b = new B // newbie :P
// now no access to b
// I want:
B.prototype.__proto__ = C.prototype
// now yes access to b
b.c() // prints C
Upvotes: 1
Views: 44
Reputation: 72857
You were close: You can replace the method through B
's prototype
:
class B { c() { console.log('B') ;} }
const b = new B();
B.prototype.c = () => { console.log("C"); }
b.c() // prints C
You can't just replace the whole prototype, you'd really need to change the properties on the prototype:
class B { c() { console.log('B') ;} }
class C { c() { console.log('C') ;} }
const b = new B();
B.prototype = C.prototype;
b.c() // This still prints `B`
Upvotes: 2