Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace javascript prototype with custom function

// 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,'')
like image 705
Billy Moon Avatar asked Apr 07 '12 20:04

Billy Moon


People also ask

Should you use prototype in JavaScript?

There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.

How replace method works in JavaScript?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do you replace something in JavaScript?

To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.

Do functions have a prototype?

Every function has the "prototype" property even if we don't supply it. The default "prototype" is an object with the only property constructor that points back to the function itself. We can use constructor property to create a new object using the same constructor as the existing one.


1 Answers

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.
like image 89
Rob W Avatar answered Oct 11 '22 19:10

Rob W