Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I access JavaScript Class and it's methods in browser Window object?

I have a JavaScript class that I want to read and set a property called selection of it from another file, and I was trying to access the class/methods from the browser window object, but the class doesn’t show up there.

I see other classes like JQuery. How can I get my class to show up in the window for global access?

Here’s what I was hoping to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class UI {
    constructor() {
        this.selection = {}; // I want to read and set this property
    }

}

And from another file, I was hoping to do something like this:

if( window.UI.selection.name ) {
    window.UI.selection.name = 'A new name';
};

Is there a way to make a class globally accessible in the window?

>Solution :

If you want to define a class and use its own instance variable, you can do this

class UI {
    constructor() {
        this.selection = {}; // I want to read and set this property
    }
}

window.UI = new UI()
window.UI.selection.name = "foo"
console.log(window.UI.selection.name)

If you want to use class without new but with static variable, you can write the following:

class UI {
    static selection = {}
}

window.UI = UI
window.UI.selection.name = "foo"
console.log(window.UI.selection.name)

Refrence:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading