Akos
Akos

Reputation: 43

How to call or access a class method in JavaScript from the browser's console?

I am learning JavaScript and ran into a problem that's probably not a big deal for a more experienced eye, but it got me puzzled. So, here is a very basic example of what I'm doing. I got two files, guitars.js and script.js.

guitar.js:

class Guitars {
    constructor(brand, model, type) {
        this.brand = brand;
        this.model = model;
        this.type = type;
    }

    changeDetails(newBrand, newModel, newType) {
        this.brand = newBrand;
        this.model = newModel;
        this.type = newType;
    }
}
export default Guitars

script.js:

import Guitars from "./guitars.js";

const newGuitar = new Guitars ("Epiphone", "Les Paul", "electric")

console.log("The new guitar: ", newGuitar)

I have this in an html file, like so:

<script type="module" src="guitars.js" defer></script>
<script type="module" src="script.js" defer></script>

When I open the console in the browser I can see that the object is created, along with all its properties, but how can I access/call that changeDetails() method?

When I put everything in the same file, I can access everything by typing:

newGuitar.changeDetails()

and it works fine. When I divide it into modules I cannot do anything.

If someone could help me with this I'd very much appreciate.

Thanks in advance.

Upvotes: 1

Views: 3039

Answers (2)

raina77ow
raina77ow

Reputation: 106453

The modules encapsulate data, essentially hiding them from global scope. If that were not the case, you'd have to worry about potential names clashing when importing other modules.

If you want to expose this data globally, you'll have to make it explicitly by assigning the exposed values to window object. For example:

window.Guitars = Guitars;

In this case you should be able to use this class (a function to call) directly in your browser's console:

enter image description here

Upvotes: 0

Jirka Svoboda
Jirka Svoboda

Reputation: 418

There are multiple possible approaches here. One of them could be to store the newGuitar instance in some global variable and then access it in your console.

So try adding this to the end of your script.js file:

window.newGuitar = newGuitar

Then in your browser console you can access the method like window.newGuitar.changeDetails()

NOTE: storing instances in global variables is not a good practice and it should be used just for some debug reasons etc…

Upvotes: 1

Related Questions