Search code examples
javascriptprototype

instanceof behavior while doing incomplete inheritance


In this example:

/**
 * Transform base class
 */
function Transform() {
    this.type = "2d";
}

Transform.prototype.toString = function() {
    return "Transform";
}

/**
 * Translation class.
 */
function Translation(x, y) {
    // Parent constructor
    Transform.call(this);

    // Public properties
    this.x = x;
    this.y = y;
}

// Inheritance
Translation.prototype = Object.create(Transform.prototype);
// Here I purposely omit Translation.prototype.constructor = Translation;

translation = new Translation(10, 15);

console.log(Translation.prototype.constructor); // Transform
console.log(translation.__proto__); // Transform
console.log(translation.constructor); // Transform

// Yet this is true!
console.log(translation instanceof Translation);

Can someone explain why translation instanceof Translation is true if neither __proto__ nor constructor contain Translation?


Solution

  • It's true because translation is an instance of Translation. In general new X instanceof X is true.

    Algorithmically it's true because Translation.prototype === Object.getPrototypeOf( translation ), and that's what the instanceof operator tests for.

    It starts there and continues down the prototype chain, so translation instanceof Transform is also true, because:

    Transform.prototype === Object.getPrototypeOf( Object.getPrototypeOf( translation ) )
    

    and translation instanceof Object is also true, because:

    Object.prototype === Object.getPrototypeOf( Object.getPrototypeOf( Object.getPrototypeOf( translation ) ) )