ES6 类扩展本机类型使实例在某些 JavaScript 引擎中出现意外行为

ES6 Class extending native type makes instanceof behave unexpectedly in some JavaScript engines?

本文关键字:引擎 JavaScript 意外 本机 扩展 类型 实例 ES6      更新时间:2023-09-26

考虑以下 ES6 类:

'use strict';
class Dummy {
}
class ExtendDummy extends Dummy {
    constructor(...args) {
        super(...args)
    }
}
class ExtendString extends String {
    constructor(...args) {
        super(...args)
    }
}
const ed = new ExtendDummy('dummy');
const es = new ExtendString('string');
console.log(ed instanceof ExtendDummy);
console.log(es instanceof ExtendString);

我的理解是两者都应该true,并且在Firefox和Chrome中它们是,但是Node说es instanceof ExtendStringfalse。其他构造函数也是如此,而不仅仅是String.

我使用的软件:

  • 带有 --harmony 标志的节点 v5.11.0。
  • 铬 50
  • 火狐 45

哪个 JavaScript 引擎是正确的,为什么?

Node 似乎不正确,es instanceof ExtendString绝对应该true(正如每个人都期望的那样)。

String[Symbol.hasInstance]不会被覆盖,Object.getPrototypeOf(es)应该被ExtendedString.prototype,因为规范在String (value)函数描述中详细说明了这一点:

  1. 返回 StringCreate( s , GetPrototypeFromConstructor(NewTarget, "%StringPrototype%" ))。

newtarget 在构造 new ExtendString('string') 实例时引用ExtendString,并且由于它是具有 .prototype 对象的构造函数,因此它将使用ExtendedString.prototype%StringPrototype作为新创建的外来 String 对象的 [[原型]]:

  1. S的 [[原型]] 内部插槽设置为 prototype