Skip to content
Advertisement

Console.log from a class’ function

I want to test if my function inside my class returns the given sentence. But if I try to test using console.log, it returns ReferenceError: rev is not defined. What am I doing wrong?

class store {
    constructor(revenue, workers) {
        this.revenue = revenue;
        this.workers = workers;
    }
}

class storeManager extends store {
    constructor(name) {
        super(revenue, workers);
        this.name = name;
    }

    rev() {
        return "The stores revenue is" + this.revenue;
    }
  
    hiredWorkers() {
        return "The store has" + this.revenue + "workers";
    }
};

console.log(rev())

I’m a fairly new programmer, so bear with me if this is a stupid question.

Advertisement

Answer

The entire point of a class is to provide a template to bundle up functionality into a self-contained object and not have globals for everything.

rev is a method that appears on instances of the class. It isn’t a global.

You have to create an instance of the class:

const myInstance = new StoreManager("some value for name");

(Note that this is going to fail because your constructor calls super() and tried to pass the values of variables which don’t exist in the constructor method).

… and then call the method on that:

const result = myInstance.rev();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement