8
// 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,'')
6
  • 4
    It works fine for me (in Firefox). It might help if you would explain what "broken" means. Commented Apr 7, 2012 at 20:08
  • 1
    Agreed, it works fine in Chrome too: jsfiddle.net/4hPhG Commented Apr 7, 2012 at 20:09
  • The only thing I can see that is wrong in your code is the missing ; on the first statement. Commented Apr 7, 2012 at 20:10
  • Your updated code is not a function. Commented Apr 7, 2012 at 20:10
  • 1
    @BillyMoon Your updated example does not make any sense. Can you elaborate it? What about showing the real code, if it's not too big? Commented Apr 7, 2012 at 20:16

1 Answer 1

28

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.
Sign up to request clarification or add additional context in comments.

2 Comments

There can be other issues. For example (just hypothetically) that replace is recursive and in certain cases calls "itself" using this.replace(...) with different parameters (except that it wouldn't call itself but another incompatible method). In general replacing a predefined method with an incompatible one is not going to work unless you also know exactly which predefined method calls which. This is not different from replacing a function with an incompatible one in a normal library without knowing the dependence graph.
This was exactly right - I was executing twice, so the original was getting overwritten. Schoolboy error. Thanks for the thorough answer with some other useful pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.