【问题标题】:Extending RegExp prototype without affecting the original behaviour在不影响原始行为的情况下扩展 RegExp 原型
【发布时间】:2016-12-30 19:22:58
【问题描述】:

我正在创建一个使用 assign 扩展 RegExp.prototype 的库:

function VerExp() {
  return Object.assign(RegExp.prototype, {
    // my methods here
  });
}

但是当我尝试使用编译功能时,这会导致奇怪的行为:

const regexp = new VerExp();
// some stuffs....
regexp.compile();

错误:

TypeError: Method RegExp.prototype.compile called on incompatible receiver [object Object]

但是,如果我创建一个新实例,扩展它并返回,将会起作用:

function VerExp() {
  const regexp = new RegExp();
  return Object.assign(regexp, {
    // my methods here
  });
}

const regexp = new VerExp();
regexp.compile();

我想了解更多错误,为什么会发生,我怎样才能使它工作扩展 RegExp 原型,而不是实例。

谢谢。

【问题讨论】:

标签: javascript regex object prototype


【解决方案1】:

那是因为Object.assign 返回属性分配给的相同对象。

Object.assign(RegExp.prototype, {
    // my methods here
});

将始终返回RegExp.prototype,因此您的函数没有多大意义。所有调用都会一次又一次地重新分配相同的属性,并返回相同的对象。

由于RegExp.prototype 不是正则表达式对象,因此尝试对其调用正则表达式方法会抛出异常。

RegExp 原型对象是一个普通对象。它不是正则表达式 实例并且没有 [[RegExpMatcher]] 内部插槽或任何 RegExp 实例对象的其他内部槽。

你可能想要的是子类RegExp

class VerExp extends RegExp {
  // my methods here
}
const regexp = new VerExp();
regexp.compile();
console.log("No error");

【讨论】:

  • 天才!谢谢 Oriol。
猜你喜欢
  • 2012-03-22
  • 2011-10-31
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
相关资源
最近更新 更多