user11417481
user11417481

Reputation: 21

JS/ import a class method into another class

Is it possible to import a method from one class into another in JS?

Say I have a class A

class A {
    someMethod(parameters){
        // some code here
    }
}

and I want to be able to alias that method in another class B, i.e.

aInstance = new A();
class B {
    anotherMethod = aInstance.someMethod;

}

I know this doesn't work, but is it a syntax issue, or is it not possible to pass methods between class objects like this?

Upvotes: 0

Views: 4334

Answers (3)

Umair Sarfraz
Umair Sarfraz

Reputation: 5953

Another way would be to define a static method on class A and then use it in B (without instantiating A).

class A {
  static someMethod() {
    console.info("Called via B!");
  }
}

class B {
  anotherMethod(...args) {
    return A.someMethod(...args);
  };
}

const b = new B();

b.anotherMethod();

Upvotes: 3

Jairo
Jairo

Reputation: 426

What you are attempting to do is not invalid syntax, though it is not the right way to do it.

First thing is you may have meant

aInstance = new A();
class B {
  anotherMethod = aInstance.someMethod;
}

which would technically work, but it's not the best way as you may have problems when using this inside the function.

What you could to to prevent issues with this is use an arrow function

class A {
  someMethod = (parameters) => {
    //... some code
  }
}

class B {
  anotherMethod = new A().someMethod;
}

Another way to go about this problem, depending on what exactly you want to achieve is to have a function exported instead of having it as a class member.

// A.js
export const someMethod = (parameters) => {

}

// B.js
import {someMethod} from './A';

class B extends A {
  anotherMethod = someMethod;
}

Finally, one more thing to consider depending on the relationship between the two classes, is if it would be wise to use inheritance

class A {
  someMethod = (parameters) => {
    //... some code
  }
}

class B extends A {
  anotherMethod = (...parameters) => {
    super.someMethod.apply(this, parameters);
  }
}

Though that way it would still be possible to call someMethod on an instance of B.

Upvotes: 1

BT101
BT101

Reputation: 3826

Use the instance:

anotherMethod = aInstance.someMethod;

instead of

anotherMethod = A.someMethod;

Upvotes: 0

Related Questions