扩展本机类型的ES6类使得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
。
My understanding is that both should be true
, and in Firefox and Chrome they are, however Node says es instanceof ExtendString
is false
. It's the same with other constructors, not just String
.
我使用的软件:
- 节点v5.11.0与
- 和谐
标志。 - Chrome 50
- Firefox 45
- Node v5.11.0 with the
--harmony
flag. - Chrome 50
- Firefox 45
哪个JavaScript引擎是正确的,为什么?
Which JavaScript engine is correct and why?
推荐答案
节点似乎不正确, es instanceof ExtendString
应该是 true
(像大家都期望的那样)。
Node appears to be incorrect, es instanceof ExtendString
should definitely be true
(like everyone would expect).
String [Symbol.hasInstance]
不会被覆盖,并且 Object.getPrototypeOf(es)
应该是 ExtendedString.prototype
,因为规范详细说明 String(值)
功能描述:
String[Symbol.hasInstance]
is not overwritten, and Object.getPrototypeOf(es)
should be ExtendedString.prototype
, as the spec details this in the String (value)
function description:
- 返回 StringCreate (
s
, GetPrototypeFromConstructor (NewTarget,%StringPrototype%
)) >
- Return StringCreate(
s
, GetPrototypeFromConstructor(NewTarget,"%StringPrototype%"
)).
newtarget当您构造新的ExtendString('string')
实例时,引用 ExtendString
,因为它是使用 .prototype
对象的构造函数将使用 ExtendedString.prototype
不是%StringPrototype
作为新创建的异常String对象的[[prototype]]:
The newtarget refers to ExtendString
when you construct the new ExtendString('string')
instance, and since it is a constructor with a .prototype
object it will use ExtendedString.prototype
not %StringPrototype
as the [[prototype]] for the newly created exotic String object:
- 设置[[原型]] 内部插槽
S
到原型
。
- Set the [[Prototype]] internal slot of
S
toprototype
.
这篇关于扩展本机类型的ES6类使得instanceof在某些JavaScript引擎中出人意料地出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!