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

Bil*_*oon 7 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
String.prototype.replace = {}
Run Code Online (Sandbox Code Playgroud)

下一行现在已经破了 - 我该如何解决?

"lorem ipsum".replaceOriginal(/(orem |um)/g,'')
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 20

唯一可能的问题是您的代码执行了两次,这会导致问题:真正的原始内容.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);
Run Code Online (Sandbox Code Playgroud)
  • 这允许多个方法修改而不破坏现有功能
  • 上下文由.apply()以下内容保留:通常,this对象对于(原型)方法至关重要.