Overwrite function of existing object in javascript

Consider the following code:

mynamespace.myclass = function() { this.myfunction = function() { alert("Original"); } } 

What I'm trying to do is rewrite myfunction from outside the mynamespace.myclass declaration.

When adding new functions through the prototype, it seems to work fine, if I define a function with the same name, the original function is not overwritten:

mynamespace.myclass.prototype.myfunction = function () {warning ("Overwrite"); }

Any ideas?

+4
source share
1 answer

This is because myfunction added in the constructor, which happens after the prototype properties are added (so that the "Original" actually rewrites "Overwritten").

You will have to imitate this behavior by overwriting mynamespace.myclass yourself:

 var oldClass = mynamespace.myclass; // Copy original before overwriting mynamespace.myclass = function () { // Apply the original constructor on this object oldClass.apply(this, arguments); // Now overwrite the target function after construction this.myfunction = function () { alert("Overwritten"); }; }; mynamespace.prototype = oldClass.prototype; // Same prototype 
+12
source

Source: https://habr.com/ru/post/1338842/


All Articles