Determining the super-types

# Axel Rauschmayer (14 years ago)

It might make sense to provide this as standard functionality:

  • Testing if one type is a subtype of another type.
  • Returning all supertypes of a given type.

This is especially useful if a type can significantly change the behavior of its subtypes and if there should ever be several ways of handling inheritance in ES.

# Dean Landolt (14 years ago)

On Fri, Oct 21, 2011 at 1:37 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

It might make sense to provide this as standard functionality:

  • Testing if one type is a subtype of another type.
  • Returning all supertypes of a given type.

This is especially useful if a type can significantly change the behavior of its subtypes and if there should ever be several ways of handling inheritance in ES.

What are you suggesting exactly? Javascript doesn't have structural typing, sadly. But in the type system we do have instanceof and getPrototypeOf can already be used to this effect.

# Axel Rauschmayer (14 years ago)

It might make sense to provide this as standard functionality:

  • Testing if one type is a subtype of another type.
  • Returning all supertypes of a given type.

This is especially useful if a type can significantly change the behavior of its subtypes and if there should ever be several ways of handling inheritance in ES.

What are you suggesting exactly? Javascript doesn't have structural typing, sadly. But in the type system we do have instanceof and getPrototypeOf can already be used to this effect.

For example:

function inheritsFrom(constr1, constr2) { constr2.prototype.isPrototypeOf(constr2.prototype); }

# Axel Rauschmayer (14 years ago)

You wrote constr2 instead of once constr2 and once constr1.

Right. Correct version:

function inheritsFrom(sub, super) { return super.prototype.isPrototypeOf(sub.prototype); }

And doesn't your function do exactly the same thing as instanceof?

No: function isInstanceOf(instance, type) { return type.prototype.isPrototypeOf(instance); }

You could thus rewrite inheritsFrom() as follows.

function inheritsFrom2(sub, super) { return sub.prototype instanceof super; }

But I like the explicitness of the original version.