skip to Main Content

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


  1. "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:

    {
        property_name: value,
        second_property_name: value
    }
    

    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:

    var monitor = {
        Foo: class {
            constructor() {
                // etc
            }
        }  
    }
    

    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

    export class Foo {
        constructor(element_id, options) {
            // some code
        }
        init = () => {
            some code
        }
        some_function = (data) => {
            // some code
        }
    }
    
    export class Bar {
        // some code
    }
    

    main.js

    import * as monitor from "./monitor.js";
    
    const foo = new monitor.Foo();
    
    Login or Signup to reply.
  2. well we cant call it exactly like that but we can do it somehow via object literal notation

    var mynamespace = {};
    
    mynamespace.Inits = class {
      constructor(element_id, options) {
        // whatever code
      }
    
      init = () => {
        // whatever code
      }
    
      some_functions = (data) => {
        // whatever code
      }
    };
    
    mynamespace.Area = class {
      // whatever code
    };
    
    //dot notation to access classses or funcs
    
    var myhmmm = new mynamespace.Inits("elements", {});
    myhmmm.init();
    
    var myArea = new mynamespace.Area();
    // do something pls
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search