Ad

ECMAScript 6 Child Class Prints With Parents Name

- 1 answer

When I do a console.log(object) I expect to see the name of the object's class. So it seems rather unexpected that a child class carries the name of its parent.

"use strict";

class Parent {
  constructor () {
  }
}
class Child extends Parent {
  constructor () {
    super();
  }
}
class Grandchild extends Child {
  constructor () {
    super();
  }
}

var grandchild = new Grandchild();

console.log(grandchild); // Parent {}
console.log(grandchild.constructor.name); // Grandchild
console.log(grandchild instanceof Parent); // true
console.log(grandchild instanceof Child); // true
console.log(JSON.stringify(grandchild)); // {}

Is this intended behaviour? Is it the console.log that's messing it up, or does JavaScript consider instances of any descendant class to be, first and foremost, the instance of the root level class?

Ad

Answer

console is not standard, as you can see in its MDN entry. The standard way to get the class name of an instance in ES6 is to use instance.contructor.name. This is stated in the spec.

Ad
source: stackoverflow.com
Ad