1

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

1 Answer 1

2

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`

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

7 Comments

alright man, so I'd have to manually iterate through all properties, no way to do it in one go, also making sure that those methods that no longer exist are gone?
Yea, you need to replace the properties on the prototype, which would involve some manual manipulation.
k cool i'll accept this later on if no one else suggests anything else :+1: thx
If you're using jQuery, you might have some use for $.extend. Then all you need to worry about is deleting methods that no longer exist.
I can't think of a way to do that, no, @zavr.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.