0

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?

1 Answer 1

1

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 ) ) )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.