0

Imagine I have this class:

class Class {
    constructor(arg1, arg2) { arg1 = arg2};
}

Should I do this?

class Class = exports.Class {
    constructor(arg1, arg2) { arg1 = arg2};
}

Or there's another way?

Major Despard
  • 95
  • 2
  • 11
  • `class Class = exports.Class {` is a syntax error. You shouldn't write syntax errors. – Jonas Wilms Mar 16 '19 at 21:48
  • Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – noetix Mar 16 '19 at 21:49

2 Answers2

2

With export syntax, just put export before the class:

export class Class {

(this results in a named export named Class)

Or, for a default export:

export default class Class {

With module syntax, assign to module.exports, or to a property of module.exports:

module.exports = class Class {

or

module.exports.Class = class Class {
Snow
  • 3,820
  • 3
  • 13
  • 39
  • Does JavaScript has `extern`, `public` and `private`? So all the members are public? – Major Despard Mar 16 '19 at 22:29
  • Not yet, everything is public, though that may change eventually with `#` syntax. Still, it's easy to make private instance variables with a `WeakMap` indexed by `this` – Snow Mar 16 '19 at 22:35
  • how about JSX? Does it have the ability to privatize the class properties? – Major Despard Mar 16 '19 at 22:50
  • JSX is only syntax sugar over JS, so the same thing applies - it's easy to make them private with a `WeakMap`, and a similar implementation may be added to the language later – Snow Mar 16 '19 at 22:52
2

You should do like this (for other ways, check @Snow answer):

class Class {
    constructor(arg1, arg2) { arg1 = arg2};
}

module.exports = Class;
Eduardo Junior
  • 362
  • 1
  • 10
  • I asked @Snow, I'll ask your too. Are all members of a class public? Isn't that a major security breach? – Major Despard Mar 16 '19 at 22:30
  • Not a security breach. Everyone has access to your javascript if it's running in a browser, even if it's minified, so, the attributes being public doesn't matter for security issues. Typescript has private attribute, you can take advantage of that to make encapsulation, but just for that. Using private attributes doesn't matter for security. – Eduardo Junior Mar 16 '19 at 23:45