Jayy
Jayy

Reputation: 14798

Use switch statement for identifying type of instance of object - not working

I tried to follow this previous question.

var Animal = function(){}

var Dog = function(){}
Dog.prototype = Object.create(Animal.prototype);

var dog = new Dog();

switch(dog.constructor){
    case Dog:
        console.log("Good Dog")
        break;
    default:
        console.log("Bad Dog");
}

It logs "Bad Dog".

What am I doing wrong?

Upvotes: 0

Views: 3182

Answers (3)

Gaurav Pandvia
Gaurav Pandvia

Reputation: 815

Just remove the line

Dog.prototype = Object.create(Animal.prototype);

The Object to create seems to give the Dog class the type of Object class. There is a way to determine a class name for an object by

Object.prototype.toString.call(obj)

It returns a string in the following format: '[object ' + valueOfClass + ']', e.g [object String] or [object Array]. In your case instead of returning Dog class, it was returning Object class due to the topmost line overriding your Dog class.

For preserving inheritance of Animal class into Dog Class and getting the desired result as per Harangue answer, putting the line below inheritance.

 Dog.prototype = Object.create(Animal.prototype);
 Dog.prototype.constructor = Dog; 

https://jsfiddle.net/byaqbuue/3/

Upvotes: 0

Ayan
Ayan

Reputation: 2380

The contructor reference is getting overridden due to the prototypal inheritance. Check the logs in the below snippet.

var Animal = function() {}
Animal.prototype.disp = function () {
  return 'I am an Animal';
}
var Dog = function() {}
Dog.prototype = Object.create(Animal.prototype);

var someOtherAnimal = new Dog();
// On inheriting the prototypal chain, the constructor is overridden.
console.log(someOtherAnimal.constructor === Animal);
// over riding the constructor
Dog.prototype.constructor = Dog;

var someAnimal = new Dog();
console.log(someAnimal.constructor === Dog);

switch (someAnimal.constructor) {
  case Dog:
    console.log("Good Dog")
    break;
  default:
    console.log("Bad Dog");
}
// access the animal prototpe.
console.log(someAnimal.disp());

Upvotes: 2

Jack Guy
Jack Guy

Reputation: 8523

Using setting Dog's prototype to a new instance of Animal.prototype overrides Dog's constructor. That's why a typical inheritance pattern is.

var Foo = function () {};
var Bar = function () {};
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;

In your current code Dog.constructor === Animal. Modifying it as above will give you the behavior you desire.

Upvotes: 1

Related Questions