Search code examples
javascriptoopconstructorinstanceof

Why is instanceof operator considered safer than the constructor property in determining object type?


I was reading "Professional JavaScript for Web Developers" where the author says:

The constructor property was originally intended for use in identifying the object type. However, the instanceof operator is considered to be a safer way of determining type. Each of the objects in this example is considered to be both an instance of Object and an instance of Person, as indicated by using the instanceof operator like this:

alert(person1 instanceof Object);   //true
alert(person1 instanceof Person);   //true
alert(person2 instanceof Object);   //true
alert(person2 instanceof Person);   //true

Can you explain what is the concern behind not using constructor over instanceof to determine object type?

traditional example with no differences maybe like:

car instanceof Car  // true
car.constructor === Car // true

Solution

  • class A {
    
    }
    
    class B extends A {
    
    }
    
    var x = new B();
    
    console.log('instanceof A', x instanceof A);
    console.log('instanceof B', x instanceof B);
    console.log('constructor = A', x.constructor === A);
    console.log('constructor = B', x.constructor === B);

    Subclassing makes a difference