Search code examples
javascriptreactjsclasscomponentspreact

How can I call a method from an other class/component in javascript?


I am still a rookie in frontend. I have 2 NON RELATED (no parent/child relation) classes:

search.js
Class Search{
   method,
   state
}

view.js
Class view{
     content
}

I am trying to:

  • call a search.js method from view.js.
  • change state value of search.js from view.js

Additional info:

  • I have already tried using helper functions. It was not the desired solution.
  • I am using Preact which is a leightweight version of React.

Thanks!

Code:

export default class Search extends Component {
    constructor() {
        this.state = {
            input: ""
        };
    }

    search(input) {
        this.setState({ input: input });
    }
}

Solution

  • If the classes are unrelated, then there are only three ways you can use a class's methods outside the class (or, really, inside it):

    1. If it's a static method, call it directly:

      Search.theStaticMethod()
      
    2. If it's a prototype or instance method, the usual thing is to create an instance and then call the method on that instance:

      const s = new Search(/*...*/);
      s.prototypeOrInstanceMethod();
      
    3. If it's a prototype method, you can call it without creating an instance, but it's extremely likely to be incorrect to do so:

      // ALMOST CERTAINLY NOT THE RIGHT THING
      Search.prototype.prototypeMethod();
      

      There's a variation on that where you apply the method to an object, even though that object wasn't created via new Search:

      // ALMOST CERTAINLY NOT THE RIGHT THING
      const obj = {};
      Search.prototype.prototypeMethod.call(obj);
      

      The method will get the object as this, and may or may not work correctly depending on how it's written.