How to replace javascript prototype with custom function

10,249

The only possible issue is that your code is executed twice, which causes problems: The real original .replace will disappear.

To avoid such problems, I strongly recommend to replace built-in methods using the following general method:

(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);
  • This allows multiple method modifications without breaking existing functionality
  • The context is preserved by .apply(): Usually, the this object is vital for (prototype) methods.
Share:
10,249
Billy Moon
Author by

Billy Moon

CV: http://careers.stackoverflow.com/billymoon

Updated on July 07, 2022

Comments

  • Billy Moon
    Billy Moon almost 2 years
    // 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 = {}
    

    This next line is now broken - how do I fix?

    "lorem ipsum".replaceOriginal(/(orem |um)/g,'')