pingeyeg
pingeyeg

Reputation: 680

How to call a function within a class from another file

I'm trying to figure out how to accomplish the following task. I want to be able to call a function that is within a class in another file:

file1

export class Something {
  constructor() {
    ...
  }
  myFunction = () => {
    ...
  }
}

file2

import { Something } from 'file1';

export function theFunction() {
  if (condition met) {
    Something.myFunction(...) // The myFunction is saying it's not a function
  }
}

Upvotes: 0

Views: 604

Answers (1)

P Varga
P Varga

Reputation: 20229

class Canonical {      /* in ES5 */ function Canonical() {}
  myMethod() { ... }                Canonical.prototype.myMethod = function() { ... };
}

You can call that like this:

Canonical.prototype.myMethod();
// Or, to call it as a method on anObject
Canonical.prototype.myMethod.call(anObject);

What you have created however is not a method, but a property created on each individual instance, that happens to be a function:

class Unusual {                 /* in ES5 */ function Unusual() {
  myFunction = () => { ... };                  this.myFunction = function() { ... };
}                                            }

It only exists on instances and therefore you have to create one to call it:

new Unusual().myFunction();

However I can't recommend this way of defining a "method", unless you specifically need it to be pre-bound. That is useful in React.Component classes, but now with React hooks that use case is waning.

class Test {
  constructor() { this.a = '🍏'; }
  myMethod() { console.log(this.a); }
  myFunction = () => console.log(this.a);
}
const methodReference = new Test().myMethod;
try {
  methodReference(); /* This will not work.
                        This is where an instance property can be advantageous */
} catch (ex) { console.error(ex.message); }
const functionReference = new Test().myFunction;
functionReference();

Upvotes: 1

Related Questions