Javascript 在不影响原始行为的情况下扩展RegExp原型

Javascript 在不影响原始行为的情况下扩展RegExp原型,javascript,regex,object,prototype,Javascript,Regex,Object,Prototype,我正在创建一个lib,它使用assign扩展RegExp.prototype: function VerExp() { return Object.assign(RegExp.prototype, { // my methods here }); } 但当我尝试使用compile函数时,这会导致一种奇怪的行为: const regexp = new VerExp(); // some stuffs.... regexp.compile(); 错误: TypeError: Me

我正在创建一个lib,它使用assign扩展RegExp.prototype:

function VerExp() {
  return Object.assign(RegExp.prototype, {
    // my methods here
  });
}
但当我尝试使用compile函数时,这会导致一种奇怪的行为:

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原型,而不是实例


谢谢。

这是因为
Object.assign
返回属性分配给的对象

Object.assign(RegExp.prototype, {
    // my methods here
});
将始终返回
RegExp.prototype
,因此您的函数没有多大意义。所有调用将一次又一次地重新分配相同的属性,并返回相同的对象

由于不是正则表达式对象,因此尝试对其调用正则表达式方法将引发

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

您可能需要的是子类
RegExp

类VerExp扩展了RegExp{
//我的方法在这里
}
const regexp=new VerExp();
regexp.compile();

console.log(“无错误”)仅供参考,MDN建议不要使用
RegExp.compile()
,请参阅扩展
RegExp
prototype的目的是什么?我正在向prototype对象添加新行为。Genius!谢谢你,奥利奥。