Home > database >  Scope between two jQuery blocks
Scope between two jQuery blocks

Time:09-16

There's an old question which seems similar, and I imagine this is fairly elementary solution to this problem.

I have some code that I want to separate into two different files (hopefully without setting up Webpack, Parcel or some other modular system.)

I would like jQuery to be available in each file, so have wrapped each in a jQuery(($) => {}); closure.

However, when I wrap the one with the class I want to instantiate, it's no longer accessible to the code in the other closure:

File one (loads first).

jQuery(($) => {
  class someClass {
    constructor(){
      this.hello = $("#hello").html();
    }
  }
});

File two

jQuery(($) => {
  let some_instance = someClass; # is not defined
});

I think maybe I need to assign the first jQuery block to a const and bind it to the second one, but haven't figured out how yet.

CodePudding user response:

While you can assign the class in the first script to the window

jQuery(($) => {
  window.someClass = class someClass {
    constructor(){
      this.hello = $("#hello").html();
    }
  }
});

This is irregular, requires global pollution, and is somewhat weird - for something professional, I'd really recommend using Webpack (or some other module bundler) instead if at all possible. It'll make splitting off smaller maintainable modules a whole lot easier, and will permit easy minification/transpilation if desired.

Also note that you need to use new and () to invoke a class to create an instance.

const someInstance = new someClass();

(perhaps capitalize SomeClass per JS convention)

  • Related