Monday, May 20, 2024
76
rated 0 times [  82] [ 6]  / answers: 1 / hits: 46353  / 8 Years ago, mon, july 11, 2016, 12:00:00

Let's say I have a simple class like this in fileA.js:



class foo {
constructor(x) {
this.name = x
}

fooMethod(x) {
return x + 'hello';
}
}


And I want to import and use fooMethod in fileB.js like this:



import { fooMethod } from './fileA';

class bar() {
...
barMethod(x) {
return fooMethod(x);
}
}


How would I write the export in fileA to achieve this?


More From » ecmascript-6

 Answers
12

You would have to export it on the prototype. But remember that if you do that you won't call the function in the class/object context:



export foo.prototype. fooMethod


However I would recommend you to not to do so.






Okay, due to your comment you want a good way to have a common functionality for two classes, that don't extend the same base class. One simple way is to import a utility function from two classes:



foo.js



export function foo() {
return this.name;
}


a.js



import {foo} from 'foo';
export class A extends BaseA {
foo() {
foo.apply(this, arguments);
}
}


b.js



import {foo} from 'foo';
export class B extends BaseB {
foo() {
foo.apply(this, arguments);
}
}


This is a good pattern and works well for a single function, but has limits if you want to apply more complex functionality. A good way to achieve this is a mixing pattern:



foo.js



export default superClass => class extends superClass {
foo() {
return this.name;
}
};


a.js



import foo from 'foo';
export class A extends foo(BaseA) {
..
}


b.js



import foo from 'foo';
export class B extends foo(BaseB) {
..
}


This will make your mixing create a new anonymous class between your class 'A'/'B' and 'BaseA'/'BaseB', which provides the common function foo.


[#61428] Friday, July 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;