// person.js
'use strict';

module.exports = class Person {
   constructor(firstName, lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }

   display() {
       console.log(this.firstName + " " + this.lastName);
   }
}

 

// index.js
'use strict';

var Person = require('./person.js');

var someone = new Person("First name", "Last name");
someone.display();
Answer from sitrakay on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › export
export - JavaScript - MDN Web Docs
After the export keyword, you can use let, const, and var declarations, as well as function or class declarations. You can also use the export { name1, name2 } syntax to export a list of names declared elsewhere.
🌐
DEV Community
dev.to › askyt › how-to-export-a-class-in-javascript-nfm
How to export a Class in JavaScript - DEV Community
December 6, 2024 - Your detailed breakdown offers a comprehensive guide on how to use export and import directives in JavaScript, covering various syntaxes and use cases. Let's summarize and clarify some key points you've highlighted: Export before Declarations: You can export variables, functions, or classes by adding export in front of their declarations.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › modules
Export and Import
export class { // Error! (non-default export needs a name) constructor() {} } In some situations the default keyword is used to reference the default export. For example, to export a function separately from its definition:
🌐
W3Resource
w3resource.com › javascript-exercises › modules-and-imports-exports › modules-and-imports-exports-exercise-12.php
Exporting and Using Classes in JavaScript
The Person class is defined in Person.js and exported as a named export. main.js imports the Person class and extends it to create an Employee class. The Employee class adds a new property position and a new method work.
🌐
Yorkshireman
yorkshireman.github.io › javascript-class-export-patterns
Javascript Class Export Patterns
It was also very difficult to stub the feature-switches.js without injecting it as a dependency (featureSwitches.js, line 2) as opposed to having it sat inside the class as a dependency - a good example of how dependency injection makes your code easier to work with (amongst other benefits).
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript export class
How JavaScript Export Class in JavaScript | Delft Stack
February 2, 2024 - In this example, we will initiate a class User in test.mjs, which we will export.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › es6-import-and-export
ES6 Import and Export - GeeksforGeeks
January 3, 2023 - let num_set = [1, 2, 3, 4, 5]; export default function hello() { console.log("Hello World!"); } class Greeting { constructor(name) { this.greeting = "Hello, " + name; } } export { num_set, Greeting as Greet }; Note: A default export should be ...
Find elsewhere
🌐
YouTube
youtube.com › watch
Classes and module exports in javascript - YouTube
Welcome to a youtube channel dedicated to programming and coding related tutorials. We talk about tech, write code, discuss about cloud and devops. That’s wh...
Published   September 2, 2020
🌐
Ccoenraets
ccoenraets.github.io › es6-tutorial › classes
Using Classes - ECMAScript 6 Tutorial
export default class Mortgage { constructor(principal, years, rate) { this.principal = principal; this.years = years; this.rate = rate; } get monthlyPayment() { let monthlyRate = this.rate / 100 / 12; return this.principal * monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate), this.years * 12))); ...
🌐
W3docs
w3docs.com › learn-javascript › export-and-import.html
Mastering JavaScript: Export and Import Essentials
This is crucial for building applications that are easy to update and debug. ... Explanation: In this example, we define a function greet that takes a name as an argument and returns a greeting message.
🌐
DigitalOcean
digitalocean.com › community › tutorials › js-modules-es6
ES6 Modules and How to Use Import and Export in JavaScript | DigitalOcean
September 4, 2020 - default function myLogger() { console.log(myNumbers, pets); } export class Alligator { constructor() { // ... } } ... import keyword, members to be imported in curly brackets and then the location of the module relative to the current file: ... You import the default member by giving it a name ...
🌐
DEV Community
dev.to › this-is-learning › difference-between-export-as-class-and-object-in-javascript--13f5
Difference between export as class and object in javascript ? - DEV Community
December 24, 2021 - // Example.js const example = { data: {}, }; export default { setData(token, isIVToken = false) { example.data = { key: 'value' } }, getData() { return example.data }, }; Actually as I said earlier everything is object only in Javascript.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-import-class-from-another-file
Import and export Classes and Functions in JavaScript | bobbyhadz
To import a function from another file in JavaScript: Export the function from file A, e.g. export function sum() {}. Import the function in file B as import {sum} from './another-file.js'.
🌐
Javascript-coder
javascript-coder.com › js › es6-export-class
ES6: How to export a named class | JavaScript Coder
Here in the code above I created a simple export that exports a function but notice I have added the keyword default before it.
🌐
Packtpub
subscription.packtpub.com › book › web-development › 9781789800104 › 1 › ch01lvl1sec11 › classes-and-modules
Introducing ECMAScript 6 | Advanced JavaScript
A single export may be useful if you are building a module that contains a single class. There are two ways to expose the named contents of a module with the export keyword. We can export each item individually by preceding the variable or function declaration with the export keyword, or we can export an object containing the key value pairs that reference each variable and function we want exported. These two export methods are shown in the following example:
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript export
JavaScript Export
October 6, 2023 - For example: let message = 'Hi'; export { default as message };Code language: JavaScript (javascript) ... Note that if the message was exported using a named export, you would place it inside the curly braces: import { message} from 'module.js';Code ...
Top answer
1 of 5
17

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.

2 of 5
11

You can export and import class methods by instantiating the class which obviously turns it into an object and then exporting each method by destructuring them from the new instantiated object check code example below.

Destruct and export object methods like this:

class foo {
  doSomething() {
    // some stuffs
  }

  doAnotherThing() {
    // do something else
  }

}

export const { doSomething, doAnotherThing } = new foo()

Then in your file where you want to import the methods do this:

import { doSomething, doAnotherThing } from '../class/file/directory'

doSomething() // calls the method

I hope this helps

🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Modules
JavaScript modules - MDN Web Docs - Mozilla
2 weeks ago - This is possible using export syntax of the following forms in the parent module: ... For an example, see our module-aggregation directory. In this example (based on our earlier classes example) we've got an extra module called shapes.js, which aggregates all the functionality from circle.js, ...