0

If I have a JavaScript class like this:

class Foo {
    constructor() {}
}

I can instantiate it using:

const myFoo = new Foo();

But say I have a function that takes a class instantiation like myFoo as a parameter. How can I access Foo to modify it?

Julian Lachniet
  • 223
  • 4
  • 25
  • 1
    You cannot modify the class itself. How should that work? – Thallius Aug 29 '21 at 15:16
  • You can access the constructor function by the `constructor` property on the instance, eg `myFoo.constructor` – Patrick Evans Aug 29 '21 at 15:19
  • 3
    *Why* would you need to do this? Class definitions aren't generally meant to be modified in this way, and could cause serious problems later on. – esqew Aug 29 '21 at 15:20
  • @ClausBönnhoff JavaScript is a prototype-based language. And you can do changes to a class, like removing, adding, or changing functions. – t.niese Aug 29 '21 at 15:24
  • What modification do you want to do to that class and why? – t.niese Aug 29 '21 at 15:25
  • so, you want to mess with `myFoo.constructor.prototype`? – Bravo Aug 29 '21 at 15:26
  • _"How can I access Foo to modify it?"_ - are you trying to mutate the `myFoo` object? If yes, then you can create a method inside the `Foo` class and then call that method using the `myFoo` instance. Example: `myFoo.setName("some name")` – Yousaf Aug 29 '21 at 15:29
  • If you think that the answers to the duplicate question do not answer your question, you need to explicitly say why this is the case. – t.niese Aug 29 '21 at 15:35

0 Answers0