0

This is probably gonna be a duplicate, but since I haven't found anything related by quick search, I'll post it and eventually delete it.

I'm a beginner in JavaScript classes and constructors and I'm having issues in logging the exact type of an object. My scripts are:

class User{
    constructor(name, surname){
        this.name= name;
        this.surname= surname;
    }
}  

Then in the second script:

    class Room{
    constructor(){
        this.array=[];
    }

    add(user){
        this.array.push(user);
    }

    find(user){
        var value;
        for(var i in this.array){
            if(this.array[i].name== user){
                value= user;
            }
        }
        console.log(value);
    }
}

var m= new Room();

var mark= new User("Mark", "M");
var joe= new User("Joe", "J");
var sam= new User("Sam", "S");
var nil= new User("Nil", "N");

m.add(mark);
m.add(joe);
m.add(sam);
m.add(nil);

Then I'm expecting a console.log(mark) to print

User { name: "Mark", surname: "M" }

but the type seems to always be Object. Same happens if I log m, the Room-expected object, anyone can help?

davide m.
  • 452
  • 4
  • 19
  • 2
    *"I'll post it and eventually delete it."* - If you're posting a question with intentions of deleting it, that's a major red flag that what you're about to ask is a bad question. Questions on StackOverflow should be posted with the goal of helping not only yourself, but future readers. Not to mention, users earn reputation points for answering your question. If your question gets removed, so do those points, therefore you're actively discouraging users from helping you. – Tyler Roper Dec 03 '18 at 18:42
  • ^ That said, upon reading through your question, I don't think it's *too* bad. However, it lacks a [**Verifiable** Example](https://stackoverflow.com/help/mcve). `console.log(mark)` outputs exactly what you expect it to: https://jsfiddle.net/9hr4cazt/ – Tyler Roper Dec 03 '18 at 18:50

1 Answers1

0

I suppose you're using typeof to get the class name, which will always return Object on any class instance.

What you can do instead is

console.log(mark.constructor.name); // returns "User"
console.log(m.constructor.name); // returns "Room"

See also this SO answer