Hi all.
I need to know how to restore or roll back to built-in function after overriding like following example.
String.prototype.substr= function()
{ return "";}
Now I want to use the one already built-in.
I shall be very thankful if some one could help me.
Sultan Wadood

Dani AI

Generated

A few practical notes tied to the thread: once a built-in prototype method is replaced, the original implementation is gone from that runtime unless you saved a reference first or you reload/replace the environment. was right to suggest keeping the old function; confirms the issue was solved.

A safe pattern is to capture the original before changing it and then invoke that saved reference with the correct this binding. For example:

const originalSubstr = String.prototype.substr;

String.prototype.substr = function(start, length) {
  return originalSubstr.call(this, start, length);
};

Why the recursion happened: calling the method by name on any string after the override (for example someString.substr(...)) uses the current prototype entry — which at that point is your new function — so your override ends up calling itself. Calling the saved original with call or apply avoids that and preserves the receiver.

Cautions and alternatives: avoid monkey-patching built-ins in shared code — it creates subtle bugs and conflicts. If you need custom behavior, prefer a utility function, a wrapper, or use non-enumerable/Symbol keys if you absolutely must attach metadata to prototypes. Also note that substr is considered legacy; slice or substring are the modern alternatives (see MDN for details on substr and Function.prototype.call).

References: String.prototype.substr (MDN), Function.prototype.call (MDN).

Recommended Answers

All 3 Replies

Hi All.
Do any body know how to call built in function of object like substr from overridden version. I am trying following example but the function called itself recursively not the function being overridden.
String.prototype.substr= function(str)
{

return str.substr(0,5);
}

I shall be very thankful if some one could give me some hints.
Sultan Wadood.

I don't think its possible to revert to the old function unless you save it somewhere.

eg:

String.prototype._substr = String.prototype.substr;

String.prototype.substr= function()
{

return this._substr(0,5);
}

my all poste problems have been solved.
thanks for helping and your valuable time.
Sultan Wadood.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.