Arnab Das
Arnab Das

Reputation: 3728

JavaScript: 'typeof' operator does not return correct classtype

Probably I'm making a huge mistake. Currently I'm trying to declare two classes like the following. But in both the cases, 'typeof' is returning 'object'. What is the correct process to declare a class in JavaScript, so that, we can get the correct class name as by the 'typeof' operator.

var Furniture = function(legs){
  this.legs = legs;
};
Furniture.prototype.getLegs = function(){ return this.legs; };

var Chair = function(){
  Furniture.call(this, 4);
};
Chair.prototype = Object.create(Furniture.prototype);


var a = new Furniture(12);

var b = new Chair();

console.log(typeof a);
console.log(typeof b);

Thanks in advance.

Upvotes: 1

Views: 672

Answers (3)

Samuel Mebrahtu
Samuel Mebrahtu

Reputation: 36

This will work for you

    var toType = function(obj) {
        return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
   }

var b = new Chair();

console.log(toType(b));  // Chair

Visit here
typeOf Does not return correct class type

Upvotes: 1

IAfanasov
IAfanasov

Reputation: 4993

It's the correct behavior. Mozilla developer network has useful table with results description of typeof operator:

typeof return values

I think it'll be really usefull to learn about js a bit. Javascript look like simple language. It's not true. It's tricky one.

Upvotes: 1

mohamedrias
mohamedrias

Reputation: 18566

You must check instanceof instead of typeof.

typeof will give you only the data type which is object.

console.log(a instanceof Furniture);
console.log(b instanceof Chair);

Refer How do I get the name of an object's type in JavaScript? The above SO shows various ways to find the constructor name.

Upvotes: 4

Related Questions