如何在 Javascript 中覆盖本机构造函数
How to override a native constructor in Javascript
我想更改 RegExp 构造函数,以使用不区分大小写,但我无法修改源代码。
源调用:
MyExp = new RegExp("xxx","") //Native
我可以创建一个可以覆盖它的函数吗,例如
function RegExp(a,b){
return native.RegExp(a,"i")
}
这叫做monkey patching。将本机函数的旧值保存在另一个变量中。
(function(nativeRegExp) {
window.RegExp = function(a, b) {
return nativeRegExp(a, b || "i"); // default to case-insensitive
}
})(RegExp);
您可以添加一个新方法:
RegExp.i = function(a){
return new RegExp(a,"i")
}
var str = "TextToReplace";
var r = new RegExp.i("TEXTTOREPLACE");
var newStr = str.replace(r,"replaced");
console.log(newStr)
我想更改 RegExp 构造函数,以使用不区分大小写,但我无法修改源代码。
源调用:
MyExp = new RegExp("xxx","") //Native
我可以创建一个可以覆盖它的函数吗,例如
function RegExp(a,b){
return native.RegExp(a,"i")
}
这叫做monkey patching。将本机函数的旧值保存在另一个变量中。
(function(nativeRegExp) {
window.RegExp = function(a, b) {
return nativeRegExp(a, b || "i"); // default to case-insensitive
}
})(RegExp);
您可以添加一个新方法:
RegExp.i = function(a){
return new RegExp(a,"i")
}
var str = "TextToReplace";
var r = new RegExp.i("TEXTTOREPLACE");
var newStr = str.replace(r,"replaced");
console.log(newStr)