ES6 Class 扩展本机类型会使 instanceof 在某些 JavaScript 引擎中出现意外行为?
ES6 Class extending native type makes instanceof behave unexpectedly in some JavaScript engines?
考虑以下 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 ExtendString
是 false
。其他构造函数也是一样的,不仅仅是String
.
我使用的软件:
- 带有
--harmony
标志的节点 v5.11.0。
- Chrome 50
- 火狐 45
哪个 JavaScript 引擎是正确的,为什么?
节点似乎不正确,es instanceof ExtendString
绝对应该是 true
(正如大家所期望的那样)。
String[Symbol.hasInstance]
不会被覆盖,Object.getPrototypeOf(es)
应该是 ExtendedString.prototype
,因为规范在 String (value)
function description:
中详细说明了这一点
- Return StringCreate(
s
, GetPrototypeFromConstructor(NewTarget, "%StringPrototype%"
)).
当您构造 new ExtendString('string')
实例时, 指的是 ExtendString
,并且由于它是一个带有 .prototype
对象的构造函数,它将使用 ExtendedString.prototype
不是 %StringPrototype
作为新创建的奇异字符串对象的 [[原型]]:
- Set the [[Prototype]] internal slot of
S
to prototype
.
考虑以下 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 ExtendString
是 false
。其他构造函数也是一样的,不仅仅是String
.
我使用的软件:
- 带有
--harmony
标志的节点 v5.11.0。 - Chrome 50
- 火狐 45
哪个 JavaScript 引擎是正确的,为什么?
节点似乎不正确,es instanceof ExtendString
绝对应该是 true
(正如大家所期望的那样)。
String[Symbol.hasInstance]
不会被覆盖,Object.getPrototypeOf(es)
应该是 ExtendedString.prototype
,因为规范在 String (value)
function description:
- Return StringCreate(
s
, GetPrototypeFromConstructor(NewTarget,"%StringPrototype%"
)).
当您构造 new ExtendString('string')
实例时,ExtendString
,并且由于它是一个带有 .prototype
对象的构造函数,它将使用 ExtendedString.prototype
不是 %StringPrototype
作为新创建的奇异字符串对象的 [[原型]]:
- Set the [[Prototype]] internal slot of
S
toprototype
.