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?

2

2 Answers 2

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 { 
Sign up to request clarification or add additional context in comments.

4 Comments

Does JavaScript has extern, public and private? So all the members are public?
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
how about JSX? Does it have the ability to privatize the class properties?
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
2

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

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

2 Comments

I asked @Snow, I'll ask your too. Are all members of a class public? Isn't that a major security breach?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.