ECMAScript 6子类使用父类名称打印



当我执行console.log(object)时,我希望看到对象类的名称。因此,子类带有其父类的名称似乎是出乎意料的。

"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)); // {}

这是故意的行为吗?是console.log把它搞砸了,还是JavaScript认为任何子类的实例首先是根级类的实例?

console不是标准的,正如您在其MDN条目中看到的那样。在ES6中获取实例类名的标准方法是使用instance.contructor.name。这在规范中有说明。

最新更新