原型或实例上的RegExp属性(标志,源等)?

时间:2018-01-30 18:01:01

标签: javascript

即使在阅读有关正则表达式对象的部分之后,我对ES规范中RegExp对象的实现方式还有点不清楚。我假设所有属性(如flags,source,global,multiline)都是实例属性,因为它们包含特定RegExp对象的数据,但是MDN将它们列为 prototype 的属性。

这是如何工作的?它们是否被定义为原型上的访问器,用于检查隐藏实例字段的值?

2 个答案:

答案 0 :(得分:1)

这个片段几乎可以回答你的问题:



console.log(
  Object.getOwnPropertyNames(RegExp.prototype).filter(
    key => typeof Object.getOwnPropertyDescriptor(RegExp.prototype, key).get === 'function'
  )
)




答案是肯定的,RegExp.prototype为每个成员值定义getter,这些成员值从实例对象的内部槽中查找值。您也可以查看ECMAScript specification来解决这个问题。

答案 1 :(得分:1)

我认为规范很清楚。我是own properties of the RegExp instancein the constructor 或者至少,这就是ES5中的情况。从ES6开始,属性确实是getters on the prototype,它们从构造函数或.compile()访问不可变的内部插槽initialised。甚至有a note

  

在ECMAScript 2015之前,RegExp instances were specified as having the own data properties ``sourceglobalignoreCasemultiline。这些属性现在被指定为RegExp.prototype的访问器属性。

所以你的假设是有根据的,但MDN也是正确的: - )