Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import class methods in ES2015

I'm creating a method in one module:

export function myMethod() {}

And instantiating a class in another module:

import {myMethod} from './methodFile';
class MyClass {
    constructor() {}
    myMethod // doesn't work
}

Is it possible to use myMethod as part of the MyClass class?

I'm trying to create the equivalent of the following code:

class MyClass {
    constructor() {}
    myMethod() {}
}
like image 942
Elad Avatar asked Jul 16 '15 13:07

Elad


1 Answers

No, it is impossible to reference given values in class declarations.

However, class syntax is mostly syntactic sugar, and prototype inheritance works as always. You can simply put the method on the prototype object after the class definition:

import {myMethod} from './methodFile';
class MyClass {
    …
}
MyClass.prototype.myMethod = myMethod;

If your method needs to use super, you'll want to use the .toMethod method.

like image 134
Bergi Avatar answered Sep 22 '22 02:09

Bergi