如何用自定义函数替换javascript原型

如何用自定义函数替换javascript原型,javascript,prototype,Javascript,Prototype,下一行现在已断开-如何修复 // I am trying to make a clone of String's replace function // and then re-define the replace function (with a mind to // call the original from the new one with some mods) String.prototype.replaceOriginal = String.prototype.replace Str

下一行现在已断开-如何修复

// I am trying to make a clone of String's replace function
// and then re-define the replace function (with a mind to
// call the original from the new one with some mods)
String.prototype.replaceOriginal = String.prototype.replace
String.prototype.replace = {}

唯一可能的问题是代码执行了两次,这会导致问题:真正的原始
.replace
将消失

为了避免此类问题,我强烈建议使用以下通用方法替换内置方法:

"lorem ipsum".replaceOriginal(/(orem |um)/g,'')
  • 这允许在不破坏现有功能的情况下对多个方法进行修改
  • 上下文通过以下方式保存:通常,对象对于(原型)方法至关重要

它对我来说很好(在Firefox中)。如果你能解释一下“break”的意思,可能会有所帮助。同意,它在Chrome中也能正常工作:我能看到的唯一错误是代码中缺少的
在第一条语句中。您更新的代码不是函数。@Billymon您更新的示例没有任何意义。你能详细说明一下吗?如果不是太大的话,展示真实的代码怎么样?可能还有其他问题。例如(只是假设),
replace
是递归的,在某些情况下使用
this.replace(…)
使用不同的参数调用“自身”(除了它不会调用自身,而是调用另一个不兼容的方法)。一般来说,用不兼容的方法替换预定义方法是行不通的,除非您还确切地知道哪个预定义方法调用哪个。这与在不知道依赖关系图的情况下用普通库中不兼容的函数替换函数没有什么不同。这完全正确-我执行了两次,所以原始函数被覆盖了。小学生的错误。谢谢你的详尽回答和其他一些有用的提示。
(function(replace) {                         // Cache the original method
    String.prototype.replace = function() {  // Redefine the method
        // Extra function logic here
        var one_plus_one = 3;
        // Now, call the original method
        return replace.apply(this, arguments);
    };
})(String.prototype.replace);