I’m new to javascript. I have a script that contains various classes which I want to wrap inside a namespace.
After some reading I tried the below, however I get an error, "Uncaught SyntaxError: Unexpected identifier ‘Foo’. What am I doing wrong?
var monitor = {
class Foo{
constructor(element_id, options){
// some code
}
init = () => {
some code
}
some_function = (data) => {
// some code
}
}
class Bar{
// some code
}
}
2
Answers
"namespace" isn’t a term that is generally used in JavaScript.
Historically, it was sometimes used to mean "Using an object (with many properties) assigned to a single global variable instead of using many global variables".
The general syntax for creating an object is:
There are some shorthand syntaxes that can be used in object literals, but none of them are for creating a class.
You need to be explicit about the property name and use a class expression.
For example:
However – it is 2023 and we have had half a decade of good browser support for modules, a tool designed to do that organisation rather than the old hack that was "namespaces".
So don’t do that. Use modules instead.
monitor.js
main.js
well we cant call it exactly like that but we can do it somehow via object literal notation